﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using MySql.Data.MySqlClient;
using LitJson;
using System.Data;
using System.IO;

namespace MyServer
{
    public enum State {Send,Recieve}
    class Program
    {
        static void Main(string[] args)
        {
            RoomManager bs= new RoomManager();
            LogInServer ls = new LogInServer();
            MyDataBase mdb = new MyDataBase();
            Console.Read();
        }
    }
    class RoomManager//大服务器
    {
        public int Port= 7999;
        Socket ServerSocket_V4 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPAddress Address_V4 = IPAddress.Parse("172.31.26.180");
        public List<Room>  RoomList;
        public static int PoolChipCount;//奖池总数量
        public Queue<string> ChipPoolWinners;//奖池赢家信息
        public Queue<int> IsPoolChangeQueue;//奖池被改变时的奖池总数量系列
        /***********************************/
        public List<Room> EmptyRoom_Texas_2_0;//德州空房间
        public List<Room> EmptyRoom_Texas_2_1;//德州空房间
        public List<Room> EmptyRoom_Texas_2_2;//德州空房间
        public List<Room> EmptyRoom_Texas_2_3;//德州空房间
        /***********************************/

        /***********************************/
        public List<Room> EmptyRoom_Texas_3_0;//德州空房间
        public List<Room> EmptyRoom_Texas_3_1;//德州空房间
        public List<Room> EmptyRoom_Texas_3_2;//德州空房间
        public List<Room> EmptyRoom_Texas_3_3;//德州空房间
        /***********************************/

        /***********************************/
        public List<Room> EmptyRoom_Texas_4_0;//德州空房间
        public List<Room> EmptyRoom_Texas_4_1;//德州空房间
        public List<Room> EmptyRoom_Texas_4_2;//德州空房间
        public List<Room> EmptyRoom_Texas_4_3;//德州空房间
        /***********************************/

        /***********************************/
        public List<Room> EmptyRoom_Texas_5_0;//德州空房间
        public List<Room> EmptyRoom_Texas_5_1;//德州空房间
        public List<Room> EmptyRoom_Texas_5_2;//德州空房间
        public List<Room> EmptyRoom_Texas_5_3;//德州空房间
        /***********************************/

        /***********************************/
        public List<Room> EmptyRoom_21_2_0;//21点空房间
        public List<Room> EmptyRoom_21_2_1;//21点空房间
        public List<Room> EmptyRoom_21_2_2;//21点空房间
        public List<Room> EmptyRoom_21_2_3;//21点空房间
        /**********************************/

        /***********************************/
        public List<Room> EmptyRoom_21_3_0;//21点空房间
        public List<Room> EmptyRoom_21_3_1;//21点空房间
        public List<Room> EmptyRoom_21_3_2;//21点空房间
        public List<Room> EmptyRoom_21_3_3;//21点空房间
        /**********************************/

        /***********************************/
        public List<Room> EmptyRoom_21_4_0;//21点空房间
        public List<Room> EmptyRoom_21_4_1;//21点空房间
        public List<Room> EmptyRoom_21_4_2;//21点空房间
        public List<Room> EmptyRoom_21_4_3;//21点空房间
        /**********************************/

        /***********************************/
        public List<Room> EmptyRoom_21_5_0;//21点空房间
        public List<Room> EmptyRoom_21_5_1;//21点空房间
        public List<Room> EmptyRoom_21_5_2;//21点空房间
        public List<Room> EmptyRoom_21_5_3;//21点空房间
        /**********************************/
        public static RoomManager instance;
        public int RoomNumber;
        public RoomManager()
        {
            ChipPoolWinners = new Queue<string>();
            IsPoolChangeQueue=new Queue<int>();
            PoolChipCount = 500000;
            ThreadPool.SetMinThreads(100,100);
            ThreadPool.SetMaxThreads(700,700);
            instance = this;
            RoomList = new List<Room>();
            InitializeRooms();
            ServerSocket_V4.Bind(new IPEndPoint(Address_V4, Port));
            Console.WriteLine("Listening:" + Address_V4 + ":" + Port);
            ServerSocket_V4.Listen(100);
            new Thread(ConnectionListener_V4).Start();
            new Thread(ExcuteRoomListener).Start();
            new Thread(TimeCalculator).Start();
        }
        void InitializeRooms() 
        {
            EmptyRoom_Texas_2_0 = new List<Room>();
            EmptyRoom_Texas_2_1 = new List<Room>();
            EmptyRoom_Texas_2_2 = new List<Room>();
            EmptyRoom_Texas_2_3 = new List<Room>();

            EmptyRoom_Texas_3_0 = new List<Room>();
            EmptyRoom_Texas_3_1 = new List<Room>();
            EmptyRoom_Texas_3_2 = new List<Room>();
            EmptyRoom_Texas_3_3 = new List<Room>();

            EmptyRoom_Texas_4_0 = new List<Room>();
            EmptyRoom_Texas_4_1 = new List<Room>();
            EmptyRoom_Texas_4_2 = new List<Room>();
            EmptyRoom_Texas_4_3 = new List<Room>();

            EmptyRoom_Texas_5_0 = new List<Room>();
            EmptyRoom_Texas_5_1 = new List<Room>();
            EmptyRoom_Texas_5_2 = new List<Room>();
            EmptyRoom_Texas_5_3 = new List<Room>();

            EmptyRoom_21_2_0 = new List<Room>();
            EmptyRoom_21_2_1 = new List<Room>();
            EmptyRoom_21_2_2 = new List<Room>();
            EmptyRoom_21_2_3 = new List<Room>();

            EmptyRoom_21_3_0 = new List<Room>();
            EmptyRoom_21_3_1 = new List<Room>();
            EmptyRoom_21_3_2 = new List<Room>();
            EmptyRoom_21_3_3 = new List<Room>();

            EmptyRoom_21_4_0 = new List<Room>();
            EmptyRoom_21_4_1 = new List<Room>();
            EmptyRoom_21_4_2 = new List<Room>();
            EmptyRoom_21_4_3 = new List<Room>();

            EmptyRoom_21_5_0 = new List<Room>();
            EmptyRoom_21_5_1 = new List<Room>();
            EmptyRoom_21_5_2 = new List<Room>();
            EmptyRoom_21_5_3 = new List<Room>();
        }
        void TimeCalculator()
        {
            while(true)
            {
            int hour = System.DateTime.Now.Hour;
            int minute = System.DateTime.Now.Minute;
            int second = System.DateTime.Now.Second;
            if(hour==0&&minute==0&&second==0)
            {
                Console.Write(hour +":"+minute+":"+second);
                MyDataBase.instance.ResetTableValues();
            }
            Thread.Sleep(1000);
            }
        }
        public void ConnectionListener_V4()
        {
            while (true)
            {
                try
                {
                    Socket ClientSocket = ServerSocket_V4.Accept();
                    byte[] buffer = new byte[1024];
                    ClientSocket.NoDelay = true;
                    int count = ClientSocket.Receive(buffer);
                    string msg = Encoding.ASCII.GetString(buffer, 0, count);
                    JsonData jd = JsonMapper.ToObject(msg);
                    int RoomSize = (int)jd["RoomSize"];
                    int RoomLevel = (int)jd["RoomLevel"];
                    int Scale = (int)jd["Scale"];
                    int type = (int)jd["GameType"];
                    int MinChipCount = (int)jd["limit"];
                    string property = (string)jd["Msg"];
                    if (type == 0)
                    {
                        switch (RoomSize)
                        {
                            case 2:
                                switch (RoomLevel)
                                {
                                    case 0:
                                        AcceptNewPlayer(EmptyRoom_Texas_2_0, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 1:
                                        AcceptNewPlayer(EmptyRoom_Texas_2_1, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 2:
                                        AcceptNewPlayer(EmptyRoom_Texas_2_2, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 3:
                                        AcceptNewPlayer(EmptyRoom_Texas_2_3, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                }
                                break;
                            case 3:
                                switch (RoomLevel)
                                {
                                    case 0:
                                        AcceptNewPlayer(EmptyRoom_Texas_3_0, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 1:
                                        AcceptNewPlayer(EmptyRoom_Texas_3_1, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 2:
                                        AcceptNewPlayer(EmptyRoom_Texas_3_2, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 3:
                                        AcceptNewPlayer(EmptyRoom_Texas_3_3, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                }
                                break;
                            case 4:
                                switch (RoomLevel)
                                {
                                    case 0:
                                        AcceptNewPlayer(EmptyRoom_Texas_4_0, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 1:
                                        AcceptNewPlayer(EmptyRoom_Texas_4_1, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 2:
                                        AcceptNewPlayer(EmptyRoom_Texas_4_2, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 3:
                                        AcceptNewPlayer(EmptyRoom_Texas_4_3, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                }
                                break;
                            case 5:
                                switch (RoomLevel)
                                {
                                    case 0:
                                        AcceptNewPlayer(EmptyRoom_Texas_5_0, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 1:
                                        AcceptNewPlayer(EmptyRoom_Texas_5_1, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 2:
                                        AcceptNewPlayer(EmptyRoom_Texas_5_2, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 3:
                                        AcceptNewPlayer(EmptyRoom_Texas_5_3, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                }
                                break;
                        }
                    }
                    else if (type == 1)
                    {
                        switch (RoomSize)
                        {
                            case 2:
                                switch (RoomLevel)
                                {
                                    case 0:
                                        AcceptNewPlayer(EmptyRoom_21_2_0, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 1:
                                        AcceptNewPlayer(EmptyRoom_21_2_1, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 2:
                                        AcceptNewPlayer(EmptyRoom_21_2_2, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 3:
                                        AcceptNewPlayer(EmptyRoom_21_2_3, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                }
                                break;
                            case 3:
                                switch (RoomLevel)
                                {
                                    case 0:
                                        AcceptNewPlayer(EmptyRoom_21_3_0, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 1:
                                        AcceptNewPlayer(EmptyRoom_21_3_1, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 2:
                                        AcceptNewPlayer(EmptyRoom_21_3_2, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 3:
                                        AcceptNewPlayer(EmptyRoom_21_3_3, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                }
                                break;
                            case 4:
                                switch (RoomLevel)
                                {
                                    case 0:
                                        AcceptNewPlayer(EmptyRoom_21_4_0, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 1:
                                        AcceptNewPlayer(EmptyRoom_21_4_1, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 2:
                                        AcceptNewPlayer(EmptyRoom_21_4_2, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 3:
                                        AcceptNewPlayer(EmptyRoom_21_4_3, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                }
                                break;
                            case 5:
                                switch (RoomLevel)
                                {
                                    case 0:
                                        AcceptNewPlayer(EmptyRoom_21_5_0, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 1:
                                        AcceptNewPlayer(EmptyRoom_21_5_1, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 2:
                                        AcceptNewPlayer(EmptyRoom_21_5_2, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                    case 3:
                                        AcceptNewPlayer(EmptyRoom_21_5_3, RoomSize, ClientSocket, type, property, RoomLevel, Scale, MinChipCount);
                                        break;
                                }
                                break;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                }
            }
        }
        void AcceptNewPlayer(List<Room> lst, int RoomSize, Socket ClientSocket, int GameType, string property, int level, int Scale, int MinChipCount)//处理玩家刚连接服务器的一系列过程
        {
            if(lst.Count!=0)
            {
             if(!lst[0].TheRoomIsEmpty)
             {
                 lst.Remove(lst[0]);
             }
            }
            if(lst.Count==0)
            {
                Room er = new Room(RoomSize, GameType, level, Scale, MinChipCount);
                RoomList.Add(er);
                lst.Add(er);
                Random r=new Random();
                er.RoomNumber = RoomNumber;
                RoomNumber += 1;
            }
            Room ss = lst[0];
            ss.ResetReadyCounter();
            /************/
            int SitNumber = ss.GetSitNumber();
            Player p = new Player(false, ss, SitNumber, property);
            ss.players[SitNumber]=p;
            ss.UnRemovablePlayers[SitNumber] = p;
            ss.ClientSockets[SitNumber] = ClientSocket;
            ss.dic.Add(ClientSocket,0);
            /************/
            ss.Command_0(p);
            ss.Command_1(ClientSocket);
            ss.StateTimeCounter = 0;
            ss.Cmd_500();
            ss.state = State.Recieve;
            ss.BeginToRecieveRequest(p.SitNumber,ClientSocket);
            if(ss.GetNotNullSocketsCount()==ss.RoomSize)
            {
                lst.Remove(ss);
                ss.IsInEmptyRoomList = false;
            }
        }
        void ExcuteRoomListener()//执行各小服务器端ListenMsgQueue函数
        {
            int n = 30;
            while(true)
            {
                int m = 0;
                if (IsPoolChangeQueue.Count > 0)
                {
                    m = IsPoolChangeQueue.Dequeue();
                }
                for (int i = 0; i < RoomList.Count;i++)
                {
                    if(ChipPoolWinners.Count>0)
                    {
                        RoomList[i].CommandQueue.Enqueue(ChipPoolWinners.Dequeue());
                    }
                    try
                    {
                        if (m != 0)
                        {
                            RoomList[i].Cmd_35(m);
                        }
                        RoomList[i].ListenMsgQueue(n);
                    }
                    catch(Exception e) 
                    {
                        RoomList[i].CloseTheRoom();
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.StackTrace);
                    }
                }
                Thread.Sleep(n);
            }
        }
    }
    class Room//小服务器
    {
        public List<Socket> ClientSockets;//保存真人玩家的通信套接字
        public int RoomSize;//房间的最大人数
        public string deck;//一副牌
        public List<Player> players;//保存当前已进入游戏的玩家的信息
        public List<Player> UnRemovablePlayers;//不能从中移除的玩家的集合
        public int GameType;//当前的游戏类型
        private List<Player> AIPlayers;//保存AI玩家
        public Queue<string> RequestQueue;//请求队列
        public Queue<string> CommandQueue;//命令队列
        private int  PlayerOperationCount;//玩家操作完成数量
        private int CurrentPlayerIndex;//players的当前索引
        private int DeckIndex;//当前牌的索引
        public int CurrentMinBet;//当前最小下注数
        public int CurrentMinRaise;//当前最小加注数
        public string OriginCode;//当前加注节点
        public int Step;//当前游戏的进度
        public int MinChipCount;//玩家进入游戏时身上最起码有MinCHipCount个筹码
        public int Scale;//筹码比例
        public int IsPlayerAllIn;//是不是某个玩家全押了
        public int UpperLimit;//房间下注上限
        private int Is_A;//庄家的明牌是不是A
        /*****************计时用的变量列表***************************/
        private bool IsGameOver;//游戏结束了吗
        private int Counter;//计时器
        private bool IsCounting;//是不是在计时
        public int AIOperationTime;//AI几秒钟之后尽心操作
        public int AIJoinGameTime;//AI生成时间
        public bool IsAIOperation;//判断是不是AI操作计时(还是AI生成时间计时)
        public int RoomLevel;//房间的等级
        public int PlayerOpTimeCounter;//玩家操作时间计数器
        public bool IsCountingOpTime;//判断要不要计时
        public int SecondCounter;//记录每个一秒
        public bool TheRoomIsEmpty;//判断这个房间是不是已经加入了AI
        public int Number;//倒计时记到几的数字
        public int ReadySecondCounter;//倒计时秒的记录
        public bool IsInEmptyRoomList;//记录是不是在空房间队列
        public int StateTimeCounter;//状态计时器
        public int ReconnectCounter;//重连计时器
        public State state;//状态查询状态（发数据或者等待数据过来）
        public Dictionary<Socket, int> dic;
        public List<Socket> UnResponsePlayerList;//卡住玩家的集合
        public int  RoomNumber;
        /************************************************************/
        public Room(int num,int type,int level,int scale,int _MinChipCount)//实例化一个房间服务器
        {
            UnResponsePlayerList = new List<Socket>();
            dic = new Dictionary<Socket, int>();
            ClientSockets = new List<Socket>();
            players = new List<Player>();
            UnRemovablePlayers = new List<Player>();
            AIPlayers = new List<Player>();
            RequestQueue = new Queue<string>();
            CommandQueue = new Queue<string>();
            RoomSize = num;
            RoomLevel=level;
            Scale = scale;
            Step = 0;
            UpperLimit = 20*Scale;
            MinChipCount = _MinChipCount;
            CurrentMinBet =Scale;
            deck = GetDeck();
            players = new List<Player>();
            GameType = type;
            OriginCode = "111111";
            InitializeLists();
            IsCounting = true;
            AIJoinGameTime = 10000;
            TheRoomIsEmpty = true;
            IsInEmptyRoomList = true;
            Number = 10;
        }
        void CheckPlayersGameState(int n) 
        {
            for (int i = 0; i < players.Count;i++ )
            {
                if(players[i]==null)
                {
                    continue;
                }
                if(!players[i].IsAI)
                {
                    players[i].CountTimeWhenPauseGame(n);
                }
            }
        }
        void Timer(int n) {
            CountOpTime(n);
            CheckPlayersGameState(n);
            StateChecker(n);
            if(!IsCounting)
            {
                return;
            }
            Counter += n;
            if(IsAIOperation)
            {
                if(Counter>=AIOperationTime)
                {
                players[CurrentPlayerIndex].ExcuteMyOpThread();
                Counter = 0;
                IsCounting = false;
                IsAIOperation = false;
                }
            }
            else
            {
                if(IsGameOver)
                {
                    if (Counter>=3000)
                    {
                        Counter = 0;
                        Cmd_12();
                        Cmd_300();
                    }
                }
                else 
                {
                    ReadySecondCounter += n;
                    if(ReadySecondCounter>=1000)
                    {
                        Number -= 1;
                        Cmd_300();
                        ReadySecondCounter = 0;
                    }
                    if(Counter>=AIJoinGameTime-200)
                    {
                        KickPlayers(true);
                    }
                    if(Counter >= AIJoinGameTime)
                    {
                    GetAI();
                    IsCounting = false;
                    ResetReadyCounter();
                    }
                }
                 
            }
            
        }
        void CountOpTime(int n)//计数
        {
            if(!IsCountingOpTime)
            {
                return;
            }
            PlayerOpTimeCounter += n;
            SecondCounter += n;
            if(SecondCounter>=1000)
            {
            if (PlayerOpTimeCounter>6000)
            {
                for (int i = 0; i < AIPlayers.Count;i++ ) 
                {
                    Player p = AIPlayers[i];
                    if(p==players[CurrentPlayerIndex])
                    {
                        continue;
                    }
                    if(!p.IsAlreadySendEmoji)
                    {
                        int e = (int)((0.01f+0.001f*p.Anxiety)*1000);
                        int e1 =(int)(( 0.01f + 0.001f)*1000);
                        Random r = new Random();
                        int ee = r.Next(0, 1000);
                        if (ee > 0 && ee < e)
                        {
                            Random r3 = new Random();
                            string s = string.Format("{0}*{1}*{2}", 0, p.SitNumber, r3.Next(4,6));
                            p.SendEmojiOrGift(s);
                            p.IsAlreadySendEmoji = true;
                        }
                        else if(ee>=e&&ee<e+e1)
                        {
                            string s = string.Format("{0}*{1}*{2}*{3}",1,players[CurrentPlayerIndex].SitNumber, p.SitNumber, 3);
                            p.SendEmojiOrGift(s);
                            p.IsAlreadySendEmoji = true;
                        }
                    }
                }
                if (PlayerOpTimeCounter >= 10000)
                {
                    if(GameType==0)
                    {
                        if (!players[CurrentPlayerIndex].IsAI)
                        {
                            if(Step<3)
                            {
                                players[CurrentPlayerIndex].Call();
                            }
                            else players[CurrentPlayerIndex].Fold();
                        }
                    }
                    IsCountingOpTime = false;
                    PlayerOpTimeCounter = 0;
                }
            }
            SecondCounter = 0;
            }
        }
        void ResetAIEmojiFlag() //重置玩家的发表情权利
        {
            for (int i = 0; i < AIPlayers.Count;i++ )
            {
                AIPlayers[i].IsAlreadySendEmoji = false;
            }
        
        }
        void KickPlayers(bool IsKickWithReady)//踢出没有准备的玩家 
        {
            List<int> lst = new List<int>();
            int KickOut = 0;
            for (int i = 0; i < players.Count; i++)
            {
                if (players[i] == null)
                {
                    continue;
                }
                Player p = players[i];
                if (IsKickWithReady)
                {
                    if (!p.IsReady)
                    {
                        KickOut = -1;
                        lst.Add(p.SitNumber);
                    }
                }
                else 
                {
                if(p.IsAI)
                {
                    continue;
                }
                if(p.ChipCount<MinChipCount)
                {
                    if(ClientSockets[p.SitNumber]!=null)
                    {
                        KickOut =1;
                        lst.Add(p.SitNumber);
                    }
                }
                }
            }
            if (lst.Count != 0)
            {
                Cmd_15(lst,KickOut);
            }
        
        }
        void InitializeLists()//初始化房间里的集合 
        {
            List<Player> lst = new List<Player>();
            List<Player> lst1 = new List<Player>();
            for (int i = 0; i < RoomSize; i++)
            {
                lst.Add(null);
                lst1.Add(null);
            }
            for (int j = 0; j <UnRemovablePlayers.Count; j++)
            {
                if (UnRemovablePlayers[j]==null)
                {
                    continue;
                
                }
                int SitNumber = UnRemovablePlayers[j].SitNumber;
                if(!UnRemovablePlayers[j].IsAI)
                {
                 if(ClientSockets[SitNumber]!=null)
                 {
                     lst[SitNumber] = UnRemovablePlayers[j];
                     lst1[SitNumber] = UnRemovablePlayers[j];
                 }
                }
            }
            players = lst;
            UnRemovablePlayers = lst1;
            List<Socket> lst2 = new List<Socket>();
            for (int i = 0; i < RoomSize; i++)
            {
                lst2.Add(null);

            }
            for (int j = 0; j < ClientSockets.Count; j++)
            {
                  lst2[j] = ClientSockets[j];
            }
            ClientSockets = lst2;
        }
        int GetIndexWithSitNumber(int SitNumber)
        {
            int n = 0;
            for (int i = 0; i < players.Count; i++)
            {

                if (players[i].SitNumber == SitNumber)
                {
                    n = i;
                    break;
                }

            }
            return n;
        }
        public int GetNotNullSocketsCount()
        {
            int count = 0;
            for (int i = 0; i < ClientSockets.Count;i++ )
            {
                if(ClientSockets[i]!=null)
                {
                    count += 1;
                }
            }
            return count;

        }
        int GetSocketIndex(Socket s)
        {
            int index = 0;
            for (int i = 0; i < ClientSockets.Count; i++)
            {
                if (ClientSockets[i] == s && s!= null)
                {
                    index = i;
                    break;
                }
            }
            return index;
        }
        public void ResetReadyCounter() //重置倒计时
        {
            ReadySecondCounter = 0;
            Counter = 0;
            Number = 10;
        }
        public int GetSitNumber()//填充空的座位 
        {
            int SitNumber = 0;
            for (int i = 0; i < players.Count;i++)
            {
                if(players[i]==null){
                    SitNumber=i;
                    break;
                }
            }

            return SitNumber;
        }
        Socket GetNotNullSocket(int j)
        {
            Socket s = null;
            for (int i = j; i < ClientSockets.Count; i++)
            {
                if (ClientSockets[i] != null)
                {
                    s = ClientSockets[i];
                    break;
                }
            }
            return s;

        }
        void HandleRequest(string msg) 
        {
            if (GameType == 0)
            {
                HandleTexasRequest(msg);
            }
            else Handle21Request(msg);
            
        }//处理请求
        void HandleCommand(string msg)
        {
            JsonData jd = JsonMapper.ToObject(msg);
            int CmdId = (int)jd["CmdId"];
            byte[] b = Encoding.ASCII.GetBytes(msg);
            if (CmdId != 8 && CmdId != 9 && CmdId != 10 && CmdId != 14)
            {
                for (int i = 0; i < ClientSockets.Count; i++)
                {
                    if (ClientSockets[i] != null)
                    {
                        ClientSockets[i].BeginSend(b, 0, b.Length, SocketFlags.None, new AsyncCallback((IAsyncResult ia) => { }), null);
                    }
                }
            }
            else
            {
                Socket s = GetNotNullSocket(0);
                if (s != null)
                {
                    s.BeginSend(b, 0, b.Length, SocketFlags.None, new AsyncCallback((IAsyncResult ia) => { }), null);
                }
            }
            
           
        }//处理命令
        public void ListenMsgQueue(int n) //监听请求消息队列（有，则进行处理；无，则等待消息）
       {
            string msg = null;
            if (RequestQueue.Count > 0) //处理玩家发过来的请求
             {
                 for (int i = 0; i < RequestQueue.Count;i++)
                 {
                     msg = RequestQueue.Dequeue();
                     HandleRequest(msg);
                 }
                 
             }
             if (CommandQueue.Count > 0)//向玩家发送命令
             {
                 for (int i = 0; i < CommandQueue.Count;i++ )
                 {
                     msg = CommandQueue.Dequeue();
                     HandleCommand(msg);
                 }
            }
             Timer(n);
        }
        void HandleTexasRequest(string msg)//处理德州扑克玩家的请求
        {
            JsonData jd = JsonMapper.ToObject(msg);
            int ReqId=(int)jd["ReqId"];
            switch(ReqId)
            {
                case 0:
                    ExcuteRequest_0(jd);
                    break;
                case 1:
                    ExcuteTexasRequest_1(jd);
                    break;
                case 2:
                    ExcuteTexasRequest_2(jd);
                    break;
                case 3:
                    ExcuteTexasRequest_3(jd);
                    break;
                case 4:
                    ExcuteTexasRequest_4(jd);
                    break;
                case 5:
                    ExcuteTexasRequest_5(jd);
                    break;
                case 6:
                    Req_6(jd);
                    break;
                case 7:
                    Req_7(jd);
                    break;
                case 11:
                    Req_11(jd);
                    break;
                case 16:
                    Req_16(jd);
                    break;
                case 23:
                    Req_23(jd);
                    break;
                case 25:
                    Req_25(jd);
                    break;
                case 40:
                    Req_40(jd);
                    break;
                case 60:
                    Req_60(jd);
                    break;
                case 70:
                    Req_70(jd);
                    break;
                case 80:
                    Req_80(jd);
                    break;
                case 100:
                    Req_100(jd);
                    break;
                case 500:
                    Req_500(jd);
                    break;
            }
        }
        public void ExcuteRequest_0(JsonData jd) //执行0号请求(接受准备玩家的信息)
        { 
            string msg=(string)jd["Msg"];
            string[] t = msg.Split('*');
            int SitNumber = int.Parse(t[0]);
            int ReadyFlag = int.Parse(t[1]);
            Player p =UnRemovablePlayers[SitNumber];
            p.IsReady = true;
            PlayerOperationCount += 1;
            Command_2(SitNumber,ReadyFlag);
        }
        void ExcuteTexasRequest_1(JsonData jd)//执行1号请求(接受玩家的操作信息并告诉其他玩家）
        {
            int CurrentPlayerSitNumber=(int)jd["SitNumber"];
            if(players[CurrentPlayerIndex].SitNumber!=CurrentPlayerSitNumber)
            {
                return;
            }
            string s = (string)jd["Msg"];
            string op = s;
            int m = 0;
            if (players[CurrentPlayerIndex].IsSee)
            {
                m = 1;
            }
            int delta = 0;
            switch(s)
            {
                case "Call"://跟注
                    delta=CurrentMinBet+m*CurrentMinBet;
                    MyDataBase.instance.ChangeChipCount(players[CurrentPlayerIndex],delta);
                    break;
                case "Raise"://加注
                    OriginCode=(string)jd["OriginCode"];
                    int raise_amount = (int)jd["RaiseAmount"];
                    CurrentMinRaise= raise_amount*Scale;
                    CurrentMinBet+=CurrentMinRaise;
                    delta=CurrentMinBet+m*CurrentMinBet;
                    MyDataBase.instance.ChangeChipCount(players[CurrentPlayerIndex],delta );
                    break;
                case "Fold"://弃牌
                    break;
                case "AllIn"://全押
                    IsPlayerAllIn = 1;
                    delta = players[CurrentPlayerIndex].ChipCount;
                    MyDataBase.instance.ChangeChipCount(players[CurrentPlayerIndex],delta);
                    break;
                case "See"://看牌
                    players[CurrentPlayerIndex].IsSee = true;
                    break;
                case "Compare"://接受比牌请求
                    break;
                case "ShowDown"://开牌
                     IsCountingOpTime = false;
                     PlayerOpTimeCounter = 0;
                     ResetAIEmojiFlag();
                    break;
                case "CallBeforeCompare"://比牌前的跟注
                    delta=CurrentMinBet +m*CurrentMinBet;
                    MyDataBase.instance.ChangeChipCount(players[CurrentPlayerIndex],delta );
                    break;
                case "CallBeforeShowDown"://开牌前的跟注
                    delta = CurrentMinBet + m * CurrentMinBet;
                    MyDataBase.instance.ChangeChipCount(players[CurrentPlayerIndex],delta);
                    break;
            }
            op+="_"+delta;
            if (s == "Compare")
            {
             string ps = (string)jd["Players"];
             op += "_" + ps;
            }
            Command_7(op);
            if (s == "See" || s == "Compare" || s == "ShowDown" || s == "CallBeforeCompare" || s == "CallBeforeShowDown")
            {
                return;
            
            }
            if (s != "Fold")
            {
            CurrentPlayerIndex += 1;
            }
            else
            {
            Player p=players[CurrentPlayerIndex];
            players.Remove(p);
            if (players.Count == 1)
            {
                Command_40();
                return;
            }   
            }
            if (CurrentPlayerIndex == players.Count)
            {
                Step += 1;
                CurrentPlayerIndex = 0;
                IsCountingOpTime = false;
                PlayerOpTimeCounter = 0;
                ResetAIEmojiFlag();
                if (IsPlayerAllIn == 1)
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(ExcuteIfAllIn));
                    return;
                }
                switch(Step){
                    case 1:
                        Command_5();//发底牌
                        break;
                    case 3:
                        Command_5();//发3张公共牌牌
                        break;
                    case 5:
                        Command_5();//发转牌
                        break;
                    case 7:
                        Command_5();//发河牌
                        break;
                    case 9:
                        Command_4();
                        break;
                    case 10:
                        Command_4();
                        break;
                    case 11:
                        Command_4();
                        break;
                    case 12:
                        Command_4();
                        break;
                    case 13:
                        Command_4();
                        break;
                    case 14:
                        Command_7("ShowDown");
                        break;
                }

            }
            else
            {
                Command_4();
            }

        }
        void ExcuteIfAllIn(object o)
        {
            if (Step < 8)
            {
                while (Step < 8)
                {
                    switch (Step)
                    {
                        case 1:
                            Command_5();//发底牌
                            Thread.Sleep(3000);
                            break;
                        case 3:
                            Command_5();//发3张公共牌牌
                            Thread.Sleep(1500);
                            break;
                        case 5:
                            Command_5();//发转牌
                            Thread.Sleep(1000);
                            break;
                        case 7:
                            Command_5();//发河牌
                            Thread.Sleep(1000);
                            break;
                    }
                    Step += 2;
                }
            }
            Command_7("ShowDown");
        }
        void ExcuteTexasRequest_2(JsonData jd) //接受玩家发完牌的请求
        {
            PlayerOperationCount += 1;
            if(PlayerOperationCount==GetNotNullSocketsCount())
            {
                Step += 1;
                Command_4();//进行下一轮玩家操作
                PlayerOperationCount = 0;
            }
        }
        void ExcuteTexasRequest_3(JsonData jd) //获取AI玩家手上的牌型
        {
            Player p=players[CurrentPlayerIndex];
            int CardType = (int)jd["Msg"];
            p.CardType = CardType;
            IsAIOperation = true;
            AIOperationTime = GetRandomTime();
            IsCounting = true;
        }
        void ExcuteTexasRequest_4(JsonData jd) //获取比牌的玩家的座位号并且（胜利者座位号*失败者座位号顺序接受）
        {
            PlayerOperationCount += 1;
            if (PlayerOperationCount==GetNotNullSocketsCount())
            {
                string a = (string)jd["Msg"];
                int IsEqual=(int)jd["IsEqual"];
                GoForward(a,IsEqual);
                PlayerOperationCount = 0;
            }
           
        }
        void ExcuteTexasRequest_5(JsonData jd) //获取AI玩家手上的牌的差值
        {
            int a = (int)jd["Msg"];
            Player p = players[CurrentPlayerIndex];
            p.Difference = a;
            IsAIOperation = true;
            AIOperationTime = GetRandomTime();
            IsCounting = true;
        }
        public void CloseTheRoom() //关闭当前房间
        {
            int[] ids = new int[AIPlayers.Count];
            for (int j = 0; j < ids.Length; j++)
            {
                ids[j] = AIPlayers[j].Id;
            }
            if (GameType == 0)
            {
                RemoveFromTexasEmptyRoomQueue();
            }
            else RemoveFrom21EmptyRoomQueue();
            MyDataBase.instance.SetInGameToZero(ids);
            for (int i = 0; i < ClientSockets.Count;i++)
            {
                if(ClientSockets[i]!=null)
                {
                    ClientSockets[i].Close();
                    ClientSockets[i] = null;
                }
            }
            RoomManager.instance.RoomNumber -= 1;
            CommandQueue.Clear();
            RequestQueue.Clear();
            IsCounting = false;
            RoomManager.instance.RoomList.Remove(this);
        }
        public void BeginToRecieveRequest(int i,Socket s)//开始监听每个新加入玩家发送的消息
        {
            byte[] buf=new byte[1024*8];
            MyAsyncState ms = new MyAsyncState(i,s,buf);
            s.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), ms);
        }
        void RecieveCallBack(IAsyncResult ar)//每接受完玩家消息回调
        {
            try
            {
                MyAsyncState ms = (MyAsyncState)ar.AsyncState;
                Socket s = ms.s;
                int index = ms.Index;
                int length = s.EndReceive(ar);
                byte[] buffer = ms.buffer;
                byte[] b = new byte[length];
                for (int i = 0; i < length; i++)
                {
                    b[i] = buffer[i];
                }
                string msg = Encoding.ASCII.GetString(b);
                if(msg=="")
                {
                    s.Close();
                    ClientSockets[index] = null;
                    if(GetNotNullSocketsCount()==0)
                    {
                        CloseTheRoom();
                    }
                    else Cmd_13(index);
                    return;
                }
                dic[s] = 1;
                if(UnResponsePlayerList.Contains(s))
                {
                    UnResponsePlayerList.Remove(s);
                }
                string[] t = msg.Split('{');
                if(t.Length>2)
                {
                    for (int i = 1; i < t.Length;i++)
                    {
                        t[i]="{"+t[i];
                        RequestQueue.Enqueue(t[i]);
                    }

                }
                else RequestQueue.Enqueue(msg);
                buffer = new byte[1024 * 8];
                MyAsyncState ms1 = new MyAsyncState(index, s, buffer);
                s.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), ms1);
            }
            catch
            { 
            
            
            }
        }
        void MoveLeft()//让所有玩家在Players中的位置向左移1
        {
            Player temp = players[0];
            for (int i = 1; i < players.Count; i++)
            {
                players[i - 1] = players[i];
            }
            players[players.Count - 1] = temp;
        }
        void SetDarkPlayerAtZero(int n) //让暗注玩家放在Players中的0号索引位置
        {
            for (int i = 0; i < n;i++ )
            {
                MoveLeft();
            }
        }
        public  void Command_0(Player p) //通知其他已经连接到本服务器上的其他玩家某个玩家加入了游戏
        {
                string s= string.Format("{0}*{1}",p.SitNumber ,p.GetPlayerProperty());
                JsonData jd = new JsonData();
                jd["CmdId"] = 0;
                jd["Msg"] =s;
                for (int i = 0; i < ClientSockets.Count;i++ )
                {
                    if (ClientSockets[i] != null && i!=p.SitNumber)
                    {
                    byte[] b = Encoding.ASCII.GetBytes(jd.ToJson());
                    try 
                    {
                        ClientSockets[i].BeginSend(b, 0, b.Length, SocketFlags.None, new AsyncCallback((IAsyncResult ia) => { }), null);
                    }
                    catch(Exception e)
                    {
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.StackTrace);
                        JsonData jd1 = new JsonData();
                        jd1["ReqId"] = 16;
                        jd1["Msg"] = p.SitNumber;
                        RequestQueue.Enqueue(jd1.ToJson());
                    }
                    
                    }
                }
        }
        public void Command_1(Socket  cs)//通知新连接到本服务器上的玩家他之前有几个玩家已经在游戏中 
      {
          string s = "/";
          int sit = GetSocketIndex(cs);
          for (int i = 0; i < players.Count; i++)
          {
              if (players[i] != null &&i!= sit)
              {
              s += string.Format("{0}*{1}*{2}", players[i].SitNumber, players[i].GetPlayerProperty(),players[i].IsReady) + "/";
              }
          }
          JsonData jd = new JsonData();
          jd["CmdId"] = 1;
          jd["Msg"] = s;
          jd["SitNumber"] =GetSocketIndex(cs);
          jd["PoolChipCount"] = RoomManager.PoolChipCount;
          byte[] buffer = Encoding.ASCII.GetBytes(jd.ToJson());
          try 
          {
              cs.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback((IAsyncResult ia) => { }), null);
          }
          catch(Exception e)
          {
              Console.WriteLine(e.Message);
              Console.WriteLine(e.StackTrace);
              JsonData jd1 = new JsonData();
              jd1["ReqId"] = 16;
              jd1["Msg"] =GetSocketIndex(cs); 
              RequestQueue.Enqueue(jd1.ToJson());
          }
      }
        void Command_2(int SitNumber,int ReadyFlag) {//通知所有玩家，几号玩家准备了
          string s = string.Format("{0}*{1}", SitNumber, ReadyFlag);
          JsonData jd = new JsonData();
          jd["CmdId"] = 2;
          jd["Msg"] = s;
          CommandQueue.Enqueue(jd.ToJson());
          if (PlayerOperationCount == RoomSize)
          {
                  TheRoomIsEmpty = false;
                  IsCounting = false;
                  ResetReadyCounter();
                  PlayerOperationCount = 0;
                  Command_3();
          }

      }
        void Command_3()//所有玩家准备好后发送庄家玩家信息和一副牌
      {
          for (int i = 0; i < UnRemovablePlayers.Count;i++ )
          {
              UnRemovablePlayers[i].GameCount += 1;
              string s = string.Format("{0}*{1}*{2}","GameCount",UnRemovablePlayers[i].GameCount,UnRemovablePlayers[i].Id);
              MyDataBase.instance.Update(s,UnRemovablePlayers[i].IsAI);
          }
          JsonData jd = new JsonData();
          jd["CmdId"] = 3;
          Random r = new Random();
          int DarkPlayerSitNUmber=r.Next(1, RoomSize);
          int n = DarkPlayerSitNUmber;
          if (n == players.Count - 1)
          {
              n = 0;
          }
          else n += 1;
          SetDarkPlayerAtZero(n);
          jd["SitNumber"] = DarkPlayerSitNUmber;
          jd["Msg"] = deck;
          CommandQueue.Enqueue(jd.ToJson());
          if (GameType == 0)
          {
              Command_4();
          }
          else Cmd_4();
      }
        void Command_4() //发送该轮到执行操作的玩家信息
        {
            JsonData jd = new JsonData();
            int SitNumber = players[CurrentPlayerIndex].SitNumber;
            jd["CmdId"] = 4;
            jd["Msg"] = SitNumber;
            jd["OriginCode"] = OriginCode;
            jd["Step"] = Step;
            jd["IsPlayerAllIn"] = IsPlayerAllIn;
            Player p = players[CurrentPlayerIndex];
            CommandQueue.Enqueue(jd.ToJson());
            if (p.IsAI)
            {
                if (Step == 8)
                {
                    Command_10(p);
                }
                else Command_8(p);
            }
            else
            {
                Socket s=ClientSockets[p.SitNumber];
                if(s==null)
                {
                    if (p.IsTrustee == 0)
                    {
                        p.Fold();
                    }
                    else p.Call();
                    return;
                }
            }
            IsCountingOpTime = true;
            PlayerOpTimeCounter = 0;
        }
        void Command_5()//发送所有玩家该发牌了
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 5;
            jd["Msg"] = string.Format("{0}*{1}",Step,DeckIndex);
            switch (Step)
            {
                case 1:
                    DeckIndex += 2 * players.Count;
                    break;
                case 3:
                    DeckIndex += 3;
                    break;
                case 5:
                    DeckIndex += 1;
                    break;
                case 7:
                    DeckIndex += 1;
                    break;
            }
            CommandQueue.Enqueue(jd.ToJson());
        }
        void Command_6(){ //进入游戏的玩家数量不够并且等待时间到时在所有已经在游戏的玩家电脑上生成AI玩家
            string AI = "/";
            for (int i = 0; i < RoomSize-GetNotNullSocketsCount(); i++)
            {
                int SitNumber = GetSitNumber();
                Player p = new Player(true,this,SitNumber,"");
                players[SitNumber] = p;
                UnRemovablePlayers[SitNumber] = p;
                AIPlayers.Add(p);
                AI +=string .Format("{0}*{1}",p.SitNumber,p.GetPlayerProperty()) +"/";
            }
            JsonData jd= new JsonData();
            jd["CmdId"] = 6;
            jd["Msg"] = AI;
            CommandQueue.Enqueue(jd.ToJson());
            for (int i = 0; i <AIPlayers.Count;i++ )
            {
                Player p = AIPlayers[i];
                Random r = new Random();
                double e = 0.005f;
                e += p.FriendlyDegree * 0.005f;
                double n = r.NextDouble();
                if (n > 0 && n < e)
                {
                    string k = string.Format("{0}*{1}*{2}",0,p.SitNumber,3);
                    p.SendEmojiOrGift(k);
                }
            }
           
        }
        public void Cmd_35(int n) //奖池被改变时或者新玩家加入时给所有玩家发奖池总数量
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 35;
            jd["Msg"] = n;
            CommandQueue.Enqueue(jd.ToJson());
        
        }
        void Command_7(string op) //通知所有其他玩家某个玩家执行了某个操作
       {
           JsonData jd = new JsonData();
           jd["CmdId"] = 7;
           jd["Msg"] = string.Format("{0}*{1}",players[CurrentPlayerIndex].SitNumber,op);
           CommandQueue.Enqueue(jd.ToJson());
       }
        void Command_8(Player p)//通知0号ClientSocket，发给我p的当前可能的牌型
      {
          JsonData jd = new JsonData();
          jd["CmdId"] = 8;
          jd["Msg"] =p.SitNumber;
          jd["Step"] = Step;
          CommandQueue.Enqueue(jd.ToJson());
      }
        void GoForward(string s,int IsEqual)//比玩牌后，程序进入主循环
       {
           string[] t = s.Split('*');
           int winner = int.Parse(t[0]);
           int loser = int.Parse(t[1]); 
          if(IsEqual==0)
          {
           Player p = UnRemovablePlayers[loser];
           int index_2 = GetIndexWithSitNumber(loser);
           if (CurrentPlayerIndex <index_2)
           {
                 CurrentPlayerIndex += 1;
           }
           players.Remove(p);
           if(players.Count==1)
           {
               Command_40();
               return;
           }
          }
          else if(IsEqual==1)
          {
           if(players.Count==2)
           {
               Command_7("ShowDown");
               IsCountingOpTime = false;
               PlayerOpTimeCounter = 0;
               return;
           }
           else CurrentPlayerIndex += 1;
          }
           if (CurrentPlayerIndex == players.Count)
           {
               Step += 1;
               CurrentPlayerIndex = 0;
           }
           Command_4();
       }
        void Command_40() //只剩下最后一个玩家，不用开牌，直接结算
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 40;
            jd["Msg"] = players[0].SitNumber;
            CommandQueue.Enqueue(jd.ToJson());
            IsCountingOpTime = false;
            PlayerOpTimeCounter = 0;
            CurrentPlayerIndex = 0;
        }
        void Req_40(JsonData jd)//结算唯一赢家的筹码
        {
            PlayerOperationCount += 1;
            if (PlayerOperationCount == GetNotNullSocketsCount())
            {
                int n = (int)jd["Msg"];
                string winner = string.Format("/{0}*{1}/0/", players[0].SitNumber, n, 0);
                JsonData jd1 = new JsonData();
                jd1["ReqId"] = 7;
                jd1["Msg"] = winner;
                RequestQueue.Enqueue(jd1.ToJson());
                PlayerOperationCount = 0;

            }
        }
        void Req_60(JsonData jd) //玩家切换程序的请求
        {
         int SitNumber=(int)jd["Msg"];
         Player p=UnRemovablePlayers[SitNumber];
         p.IsPausedGame = true;
        }
        void Req_70(JsonData jd)//玩家关闭程序的请求
        {
            int SitNumber = (int)jd["Msg"];
            Player p = UnRemovablePlayers[SitNumber];
            if (ClientSockets[SitNumber]!=null)
            {
                dic.Remove(ClientSockets[SitNumber]);
                ClientSockets[SitNumber].Close();
                ClientSockets[SitNumber] = null;
            }
            if (GetNotNullSocketsCount() == 0)
            {
                CloseTheRoom();
            }
            else Cmd_13(SitNumber);
        }
        void Req_80(JsonData jd)//玩家回到程序的请求
        {
            int SitNumber = (int)jd["Msg"];
            Player p = UnRemovablePlayers[SitNumber];
            p.StopCounting();
        }
        void Req_100(JsonData jd)//玩家已经被踢出房间 
        {
         int SitNumber=(int)jd["Msg"];
         if (ClientSockets[SitNumber] != null)
         {
             ClientSockets[SitNumber].Close();
             dic.Remove(ClientSockets[SitNumber]);
             ClientSockets[SitNumber] = null;
            
         }
         players[SitNumber] = null;
         UnRemovablePlayers[SitNumber] = null;
         if(GetNotNullSocketsCount()==0)
         {
             CloseTheRoom();
             return;
         }
         if(!IsInEmptyRoomList)
         {
             if (GameType == 0)
             {
                 MakeItselfAsEmptyTexasRoom();
             }
             else MakeItselfAsEmpty21Room();
         }

        }
        void Cmd_300()//发倒计时 
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 300;
            jd["Msg"] = Number;
            CommandQueue.Enqueue(jd.ToJson());
        }
        void Command_10(Player p)//通知0号ClientSocket,计算差值发给我
       {
           JsonData jd = new JsonData();
           jd["CmdId"] = 10;
           jd["Msg"] =p.SitNumber;
           CommandQueue.Enqueue(jd.ToJson());
       }
        void Command_11(string msg)// 通知所有玩家几号玩家向几号玩家发表情或者礼品
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 11;
            jd["Msg"] = msg;
            CommandQueue.Enqueue(jd.ToJson());
        }
        void Cmd_12( )//通知所有玩家AI要离开房间了
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 12;
            int[] ids = new int[AIPlayers.Count];
            for (int i = 0; i < AIPlayers.Count; i++)
            {
                ids[i] = AIPlayers[i].Id;
                players.Remove(AIPlayers[i]);
            }
            MyDataBase.instance.SetInGameToZero(ids);
            if (GameType == 0)
            {
                MakeItselfAsEmptyTexasRoom();
            }
            else MakeItselfAsEmpty21Room();
            TheRoomIsEmpty = true;
            CommandQueue.Enqueue(jd.ToJson());
            KickPlayers(false);
            ReSetTheRoom();
            IsCounting = true;
        }
        public void Cmd_13(int SitNumber) //通知所有在线的玩家几号玩家掉线了
        {
            if (UnRemovablePlayers[SitNumber]!=null)
            {
                UnRemovablePlayers[SitNumber].IsConnecting = false;
            }
            JsonData jd = new JsonData();
            jd["CmdId"] = 13;
            jd["Msg"] =SitNumber;
            CommandQueue.Enqueue(jd.ToJson());
        }
        void Cmd_14() //告诉我赢家
         {
             JsonData jd = new JsonData();
             jd["CmdId"] = 14;
             CommandQueue.Enqueue(jd.ToJson());
         }
        void Cmd_21()//开始比牌 
         {
             JsonData jd = new JsonData();
             jd["CmdId"] = 21;
             CommandQueue.Enqueue(jd.ToJson());
         }
        public  void Cmd_15(List<int> lst,int _KickOut)//通知所有没有准备的玩家被踢出房间了 
         {
             ResetReadyCounter();
             JsonData jd = new JsonData();
             jd["CmdId"] = 15;
             string s = "/";
             for (int i = 0; i < lst.Count; i++)
             {
                 if (!UnRemovablePlayers[lst[i]].IsThePlayerKickOut)
                 {
                     UnRemovablePlayers[lst[i]].IsThePlayerKickOut = true;
                 }
                 else 
                 {
                     JsonData jd1 = new JsonData();
                     jd1["ReqId"] = 16;
                     jd1["Msg"] = lst[i];
                     RequestQueue.Enqueue(jd1.ToJson());
                 }
                 s += lst[i] + "/";
             }
             jd["Msg"] = s;
             jd["KickOut"] = _KickOut;
             CommandQueue.Enqueue(jd.ToJson());
         }
        void GetAI() //获取AI
        {
            if (GameType == 0)
            {
                RemoveFromTexasEmptyRoomQueue();
            }
            else RemoveFrom21EmptyRoomQueue();
            TheRoomIsEmpty = false;
            if (PlayerOperationCount==RoomSize)
            {
                PlayerOperationCount = 0;
                Command_3();
                return;
            }
            Command_6();//让所有玩家在自己电脑上生成RoomSize-ClientSockets.Count个数的电脑AI
        }
        void ReSetTheRoom()
        {
            for (int i = 0; i < UnRemovablePlayers.Count;i++ )
            {
                if(UnRemovablePlayers[i].IsAI)
                {
                    UnRemovablePlayers[i] = null;
                }
                else if (!UnRemovablePlayers[i].IsConnecting) 
                {
                    UnRemovablePlayers[i] = null;
                }
            }
            InitializeLists();
            for (int i = 0; i < players.Count; i++)
            {
                if (players[i] != null)
                {
                    players[i].IsReady = false;
                }
            }
            PlayerOperationCount = 0;
            IsPlayerAllIn = 0;
            Step = 0;
            AIPlayers.Clear();
            CurrentPlayerIndex = 0;
            OriginCode = "111111";
            deck = GetDeck();
            DeckIndex = 0;
            CurrentMinBet = Scale;
            IsGameOver = false;
        }
        void RemoveFromTexasEmptyRoomQueue()//当前德州房间空房队列中移除
        {
            switch (RoomSize)
            {
                case 2:
                    switch(RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_Texas_2_0.Remove(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_Texas_2_1.Remove(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_Texas_2_2.Remove(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_Texas_2_3.Remove(this);
                            break;
                    }
                    
                    break;
                case 3:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_Texas_3_0.Remove(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_Texas_3_1.Remove(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_Texas_3_2.Remove(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_Texas_3_3.Remove(this);
                            break;
                    }
                    break;
                case 4:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_Texas_4_0.Remove(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_Texas_4_1.Remove(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_Texas_4_2.Remove(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_Texas_4_3.Remove(this);
                            break;
                    }
                    break;
                case 5:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_Texas_5_0.Remove(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_Texas_5_1.Remove(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_Texas_5_2.Remove(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_Texas_5_3.Remove(this);
                            break;
                    }
                    break;
            }
        }
        void RemoveFrom21EmptyRoomQueue()////当前21点房间空房队列中移除
        {
            if (GetNotNullSocketsCount() == RoomSize)
            {
                return;
            }
            switch (RoomSize)
            {
                case 2:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_21_2_0.Remove(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_21_2_1.Remove(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_21_2_2.Remove(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_21_2_3.Remove(this);
                            break;
                    }
                    break;
                case 3:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_21_3_0.Remove(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_21_3_1.Remove(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_21_3_2.Remove(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_21_3_3.Remove(this);
                            break;
                    }
                    break;
                case 4:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_21_4_0.Remove(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_21_4_1.Remove(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_21_4_2.Remove(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_21_4_3.Remove(this);
                            break;
                    }
                    break;
                case 5:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_21_5_0.Remove(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_21_5_1.Remove(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_21_5_2.Remove(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_21_5_3.Remove(this);
                            break;
                    }
                    break;
            }
           
        }
        void MakeItselfAsEmptyTexasRoom()//把自己加入到德州空房队列
        {
            if(GetNotNullSocketsCount()==RoomSize)
            {
                return;
            }
            switch (RoomSize)
            {
                case 2:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_Texas_2_0.Add(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_Texas_2_1.Add(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_Texas_2_2.Add(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_Texas_2_3.Add(this);
                            break;
                    }

                    break;
                case 3:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_Texas_3_0.Add(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_Texas_3_1.Add(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_Texas_3_2.Add(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_Texas_3_3.Add(this);
                            break;
                    }
                    break;
                case 4:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_Texas_4_0.Add(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_Texas_4_1.Add(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_Texas_4_2.Add(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_Texas_4_3.Add(this);
                            break;
                    }
                    break;
                case 5:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_Texas_5_0.Add(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_Texas_5_1.Add(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_Texas_5_2.Add(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_Texas_5_3.Add(this);
                            break;
                    }
                    break;
            }
            IsInEmptyRoomList = true;
        }
        void MakeItselfAsEmpty21Room()//把自己加入到21空房队列
        {
            if (GetNotNullSocketsCount() == RoomSize)
            {
                return;
            }
            switch (RoomSize)
            {
                case 2:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_21_2_0.Add(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_21_2_1.Add(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_21_2_2.Add(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_21_2_3.Add(this);
                            break;
                    }
                    break;
                case 3:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_21_3_0.Add(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_21_3_1.Add(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_21_3_2.Add(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_21_3_3.Add(this);
                            break;
                    }
                    break;
                case 4:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_21_4_0.Add(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_21_4_1.Add(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_21_4_2.Add(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_21_4_3.Add(this);
                            break;
                    }
                    break;
                case 5:
                    switch (RoomLevel)
                    {
                        case 0:
                            RoomManager.instance.EmptyRoom_21_5_0.Add(this);
                            break;
                        case 1:
                            RoomManager.instance.EmptyRoom_21_5_1.Add(this);
                            break;
                        case 2:
                            RoomManager.instance.EmptyRoom_21_5_2.Add(this);
                            break;
                        case 3:
                            RoomManager.instance.EmptyRoom_21_5_3.Add(this);
                            break;
                    }
                    break;
            }
            IsInEmptyRoomList = true;
        }
        string GetDeck()//获取一副牌
        {
            string[] s = new  string[52];
            for (int i = 0; i < 4; i++)
            {
                string suit = "";
                switch (i)
                {
                    case 0:
                        suit = "Heart";
                        break;
                    case 1:
                        suit = "Spade";
                        break;
                    case 2:
                        suit = "Diamond";
                        break;
                    case 3:
                        suit = "Club";
                        break;
                }
                for (int j = 2; j <= 14; j++)
                {
                    s[i * 13 + j - 2] = string.Format("{0}_{1}",j,suit);
                }
            }
            for (int i = 0; i < 15;i++ )
            {

                Shuffle(s);
            }
            string cards = "/";
            for (int i = 0; i < 52;i++ )
            {
                cards += s[i] + "/";
            }
            return cards;
        }
        void Shuffle(string[] s)//扰乱牌序
        {
                Random r = new Random();
                for (int i = 0; i < 52; i++)
                {
                    int k=r.Next(52);
                    string temp = s[i];
                    s[i] = s[k];
                    s[k] = temp;
                }
        }
        /**********************************************************
         * 
         * 下面的一系列代码用于21点交互
         * 
         * ********************************************************/
        void Handle21Request(string msg)//处理21点玩家的请求
        {
            JsonData jd = JsonMapper.ToObject(msg);
            int ReqId = (int)jd["ReqId"];
            switch (ReqId)
            {
                case 0:
                    ExcuteRequest_0(jd);
                    break;
                case 1:
                    Req_1(jd);
                    break;
                case 2:
                    Req_2(jd);
                    break;
                case 9:
                    Req_9(jd);
                    break;
                case 6:
                    Req_6(jd);
                    break;
                case 7:
                    Req_7(jd);
                    break;
                case 11:
                    Req_11(jd);
                    break;
                case 16:
                    Req_16(jd);
                    break;
                case 23:
                    Req_23(jd);
                    break;
                case 60:
                    Req_60(jd);
                    break;
                case 70:
                    Req_70(jd);
                    break;
                case 80:
                    Req_80(jd);
                    break;
                case 100:
                    Req_100(jd);
                    break;
                case 500:
                    Req_500(jd);
                    break;
            }
        }
        void Req_1(JsonData jd) //执行1号请求（接受玩家的操作信息并告诉其他玩家）
        {
            string msg=(string)jd["Msg"];
            string[] t = msg.Split('*');
            string Op=t[2];
            Player p=players[CurrentPlayerIndex];
            int num = 0;
            switch(Op)
            {
                case "Call":
                    num = int.Parse(t[1]);
                    MyDataBase.instance.ChangeChipCount(p,num);
                    break;
                case "Hit":
                    msg +="*"+ DeckIndex;
                    DeckIndex += 1;
                    break;
                case "DoubleHit":
                    num = Math.Abs(int.Parse(t[1]));
                    MyDataBase.instance.ChangeChipCount(p, num);
                    msg +="*"+ DeckIndex;
                    DeckIndex += 1;
                    break;
                case "Surrender":
                    
                    break;
                case "Split":
                    num = int.Parse(t[1]);
                    if(num>0)
                    {
                        msg += "*" + DeckIndex;
                        DeckIndex += 2;
                        MyDataBase.instance.ChangeChipCount(p, num);
                    }
                    break;
                case "Stand":
                     
                    break;
                case "Insurance":
                     num = int.Parse(t[1]);
                    if(num>0)
                    {
                        MyDataBase.instance.ChangeChipCount(p, num);
                    }
                    break;
            }
            Cmd_7(msg);
            if (Op == "Stand")
            {
                num = int.Parse(t[1]);
                if (num != 0)
                {
                    Cmd_4();
                    return;
                }   
            }
                  
            if(Op=="Hit"||Op=="DoubleHit"){
                return;
            }
            if (Op != "Surrender")
            {
                CurrentPlayerIndex += 1;
            }
            else
            {
                int f = int.Parse(t[1]);
                if(f==1||f==3)
                {
                    players.Remove(p);
                    if(players.Count==1)
                    {
                        Cmd_21();
                        return;
                    }
                }
            }
            int flag = players.Count - 1;
            if(Step==6)
            {
                flag = players.Count;
            }
            if (CurrentPlayerIndex == flag)
            {
                IsCountingOpTime = false;
                PlayerOpTimeCounter = 0;
                ResetAIEmojiFlag();
                CurrentPlayerIndex = 0;
                Step += 1;
                switch (Step)
                {
                    case 1:
                        Cmd_5();
                        break;
                    case 3:
                        Cmd_4();
                        break;
                    case 4:
                        Cmd_5();
                        break;
                    case 5:
                        Cmd_4();
                        break;
                    case 6:
                        Cmd_4();
                        break;
                    case 7:
                        Cmd_21();
                        break;
                }
            }
            else Cmd_4();
        }
        void Req_2(JsonData jd) //执行2号请求（接受玩家发完牌的请求）
        {
            PlayerOperationCount += 1;
            if(PlayerOperationCount==GetNotNullSocketsCount())
            {
                PlayerOperationCount = 0;
                if (Step ==1)
                {
                    Cmd_9();
                }
                else
                {
                    Step +=1;
                    Cmd_4();
                }
            }
        }
        void Req_9(JsonData jd) //执行9号请求（获取庄家的名牌是不是A）
        {
            Is_A = (int)jd["Msg"];

            if (Is_A == 0)
            {
                Step += 2;
            }
            else Step += 1;
            Cmd_4();
        }
        void Req_6(JsonData jd)//通知服务器我已经计算好了赢家
        {
            PlayerOperationCount += 1;
            if (PlayerOperationCount == GetNotNullSocketsCount())
            {
                PlayerOperationCount = 0;
                Cmd_14();
            }
        }
        void Req_7(JsonData jd)//获取赢家信息
        { 
         string s=(string)jd["Msg"];
         string[] t = s.Split('/');
         List<int> lst = new List<int>();
         int length = t.Length -1;
         int BigCardType = 0;
         if (GameType == 0)
         {
             BigCardType = int.Parse(t[length-1]);
             length -= 1;
         }  
         for (int i = 1; i < length;i++)
         {
             Random r = new Random();
             int n = r.Next(0, 1000);
             string[] m = t[i].Split('*');
             int SitNumber = int.Parse(m[0]);
             lst.Add(SitNumber);
             int Amount= -int.Parse(m[1]);
             Player p = UnRemovablePlayers[SitNumber];
             string CardTypeStr = null;
             if(GameType==0)
             {
                 if(p.RewardPoolState==1)
                 {
                 float Percent = 0;
                 switch(BigCardType)
                 {
                     case 9:
                         Percent = 0.2f;
                         CardTypeStr = "RoyalFlush";
                         break;
                     case 8:
                         Percent = 0.1f;
                         CardTypeStr = "StraightFlush";
                         break;
                     case 7:
                         Percent = 0.05f;
                         CardTypeStr = "Four Of a Kind";
                         break;
                     case 6:
                         Percent = 0.04f;
                         CardTypeStr = "FullHouse";
                         break;
                     case 5:
                         Percent = 0.03f;
                         CardTypeStr = "Flush";
                         break;
                     case 4:
                         Percent = 0.02f;
                         CardTypeStr = "Straight";
                         break;
                     case 3:
                         Percent = 0.01f;
                         CardTypeStr = "Three Of a Kind";
                         break;
                     case 2:
                         Percent = 0.005f;
                         CardTypeStr = "Two Pairs";
                         break;
                     case 1:
                         Percent = 0.002f;
                         CardTypeStr = "Twain";
                         break;
                     case 0:
                         Percent = 0.001f;
                         CardTypeStr = "SingleBigCard";
                         break;
                 
                 }
                     int delta=(int)(RoomManager.PoolChipCount * Percent);
                     Cmd_27(string.Format("{0}*{1}",p.SitNumber,delta));
                     Amount -= delta;
                     RoomManager.PoolChipCount-=delta;
                     JsonData jd5 = new JsonData();
                     jd5["CmdId"] = 200;
                     jd5["Msg"] = string.Format("{0}*{1}*{2}", p.Name, delta,CardTypeStr);
                     RoomManager.instance.ChipPoolWinners.Enqueue(jd5.ToJson());
                     RoomManager.instance.IsPoolChangeQueue.Enqueue(RoomManager.PoolChipCount);
                 }
             }
             p.WinCount += 1;
             string s2=string.Format("{0}*{1}*{2}","WinCount",p.WinCount,p.Id);
             MyDataBase.instance.Update(s2,p.IsAI);
             MyDataBase.instance.ChangeChipCount(p,Amount);
             if(GameType==1)
             {
                 int e =(int)((0.005f + 0.005f * p.FriendlyDegree)*1000);
                 if (n > 0 && n < e)
                 {
                     Random r3 = new Random();
                     string k = string.Format("{0}*{1}*{2}", 0, p.SitNumber, r3.Next(0,4));
                     p.SendEmojiOrGift(k);
                 }
             }
         }
         for (int i = 0; i < lst.Count;i++ )
         {
             for (int j = 0; j < players.Count;j++ ) 
             { 
                 if(!players[j].IsAI)
                 {
                     continue;
                 }
                 Random r = new Random();
                 int n = r.Next(0, 1000);
                 if(GameType==0)
                 {
                     if (!IsContainsSitNumber(players[j].SitNumber)) 
                     {
                         int e1= (int)((0.01f+ 0.005f * players[j].Anxiety - 0.001f * players[j].FriendlyDegree)*1000);
                         int e2 = (int)((0.02f+0.005f * players[j].Anxiety - 0.002f * players[j].FriendlyDegree)*1000);
                         if (n > 0 && n < e1)
                         {
                             Random r3 = new Random();
                             string ss1 = string.Format("{0}*{1}*{2}", 0, players[j].SitNumber,r3.Next(4,6));
                             players[j].SendEmojiOrGift(ss1);
                         }
                         else if (n >= e1 && n < e1 + e2)
                         {
                             Random r1 = new Random();
                             int mm = r1.Next(i+1,lst.Count);
                             string ss2 = string.Format("{0}*{1}*{2}*{3}", 0,lst[mm], players[j].SitNumber,3);
                             players[j].SendEmojiOrGift(ss2);
                         }
                     }
                 }
                 else if(GameType==1)
                 {
                     if (!IsContainsSitNumber(players[j].SitNumber))
                     {
                         int  e =(int)((0.03f -0.003f * players[j].FriendlyDegree + 0.005f * players[j].Anxiety)*1000);
                         if (n > 0 && n < e)
                         {
                             Random r3 = new Random();
                             string s1 = string.Format("{0}*{1}*{2}", 0, players[j].SitNumber, r3.Next(4,6));
                             players[j].SendEmojiOrGift(s1);
                         }
                     }
                 }
             
             }

         }
         Cmd_22();
        }
        void Cmd_27(string s) //通知该奖池的玩家，他获得了多少个奖池
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 27;
            jd["Msg"] = s;
            CommandQueue.Enqueue(jd.ToJson());
        
        }
        bool IsContainsSitNumber(int SitNumber) 
        {
            for (int i = 0; i < players.Count;i++ )
            {
                if (players[i].SitNumber == SitNumber)
                {
                    return true;
                }      
              
            }

            return false;
        }
        void Req_11(JsonData jd) //获取发送和接受表情包（礼品）玩家信息
        {
            string msg = (string)jd["Msg"];
            Command_11(msg);
            string[] t = msg.Split('*');
            int id=int.Parse(t[0]);
            Random r = new Random();
            switch(id)
            {
                case 0:
                    int SitNumber = int.Parse(t[1]);
                    Player p1 = UnRemovablePlayers[SitNumber];
                    if(p1==null)
                    {
                        break;
                    }
                    if(p1.IsAI)
                    {
                        break; 
                    }
                    int Number = int.Parse(t[2]);
                    if (Number >= 0 && Number <= 3)
                    {
                        for (int i = 0; i < AIPlayers.Count; i++)
                        {
                            int n = r.Next(0, 1000);
                            Player p = AIPlayers[i];
                            int e = (int)((0.05f + p.FriendlyDegree * 0.005f) * 1000);
                            if (n > 0 && n < e)
                            {
                                Random r3 = new Random();
                                string k = string.Format("{0}*{1}*{2}", 0, p.SitNumber, r3.Next(0,4));
                                p.SendEmojiOrGift(k);
                            }
                        }
                    }
                    break;
                case 1:
                    int Reciever_sit = int.Parse(t[1]);
                    int Sender_sit = int.Parse(t[2]);
                    int GiftNumber = int.Parse(t[3]);
                    Player Reciever = UnRemovablePlayers[Reciever_sit];
                    Player Sender = UnRemovablePlayers[Sender_sit];
                    if(Reciever==null||Sender==null)
                    {
                        break;
                    }
                    int amount = 0;
                     switch (GiftNumber)
                     {
                         case 0:
                             amount = -10;
                             break;
                         case 1:
                             amount = -20;
                             break;
                         case 2:
                             amount = -30;
                             break;
                         case 3:
                             amount = 20;
                             break;
                     }
                     MyDataBase.instance.ChangeCharmValue(Reciever, amount);
                     MyDataBase.instance.ChangeChipCount(Sender, amount);
                    int m = r.Next(0, 1000);
                    if(Reciever.IsAI)
                    {
                     if(!Sender.IsAI)
                     {
                         Player p = Reciever;
                         for(int i=0;i<AIPlayers.Count;i++)
                         {
                         Random r3 = new Random();
                         if (AIPlayers[i].SitNumber == Reciever_sit)
                         {
                             if (GiftNumber >= 0 && GiftNumber <= 2)
                             {//如果是善意礼物
                                int  e=(int)((0.02f+ p.FriendlyDegree * 0.005f)*1000);
                                int  e1=(int)((0.05f +p.FriendlyDegree * 0.005f)*1000);
                                if (m > 0 && m < e)
                                 {
                                     string k = string.Format("{0}*{1}*{2}", 0,Reciever_sit, r3.Next(0, 3));
                                     p.SendEmojiOrGift(k);
                                 }
                                else if (m >= e && m < e + e1)
                                 {
                                     string k = string.Format("{0}*{1}*{2}*{3}", 1, Sender_sit, Reciever_sit, r3.Next(0, 3));
                                     p.SendEmojiOrGift(k);
                                 }
                             }
                             else
                             {
                                 int e1 =(int)(( 0.1f - p.FriendlyDegree * 0.005f)*1000);
                                 if (m > 0 && m < e1)
                                 {
                                     string k = string.Format("{0}*{1}*{2}*{3}", 1, Sender_sit, Reciever_sit, 3);
                                     p.SendEmojiOrGift(k);
                                 }
                             }
                         }
                         else 
                         {
                             int e3 = (int)((0.01f-0.001f*AIPlayers[i].FriendlyDegree)*1000);
                             if (m > 0 && m < e3)
                             {
                                 string k = string.Format("{0}*{1}*{2}*{3}", 1, Sender_sit, AIPlayers[i].SitNumber, 3);
                                 p.SendEmojiOrGift(k);
                             }
                         
                         }    
                        
                         }
                        
                     }

                    }

                    break;
             }
           
        }
        void Req_16(JsonData jd)//玩家退出房间的请求
        {
            int SitNumber = (int)jd["Msg"];
            if (ClientSockets[SitNumber]!=null)
            {
                dic.Remove(ClientSockets[SitNumber]);
                ClientSockets[SitNumber].Close();
                ClientSockets[SitNumber] = null;
            }
            UnRemovablePlayers[SitNumber].IsConnecting = false;
            if (GetNotNullSocketsCount() ==0)
            {
                CloseTheRoom();
            }
            else 
            {
                if(TheRoomIsEmpty)
                {
                    if (players[SitNumber].IsReady)
                    {
                        PlayerOperationCount -= 1;
                    }      
                    players[SitNumber] = null;
                    UnRemovablePlayers[SitNumber] = null;
                    ResetReadyCounter();
                    if(!IsInEmptyRoomList)
                    {
                        if (GameType == 0)
                        {
                            MakeItselfAsEmptyTexasRoom();
                        }
                        else MakeItselfAsEmpty21Room();
                    }
                }
                Cmd_13(SitNumber);
            }
            
        }
        void Req_23(JsonData jd)//收到玩家的托管请求
        {
            string msg=(string)jd["Msg"];
            string[] t = msg.Split('*');
            int SitNumber = int.Parse(t[0]);
            int State = int.Parse(t[1]);
            Player p = UnRemovablePlayers[SitNumber];
            p.IsTrustee = State;
            Cmd_23(msg);
        }
        void Req_25(JsonData jd) //处理玩家有没有开奖池的状态
        {
         string msg=(string)jd["Msg"];
         string[] t = msg.Split('*');
         int SitNumber = int.Parse(t[0]);
         int State = int.Parse(t[1]);
         Player p =UnRemovablePlayers[SitNumber];
         p.RewardPoolState = State;
         if(State==1)
         {
             MyDataBase.instance.ChangeChipCount(p,100);
             RoomManager.PoolChipCount+= 100;
             RoomManager.instance.IsPoolChangeQueue.Enqueue(RoomManager.PoolChipCount);
             Cmd_25(SitNumber);
         }
        }
        void Cmd_25(int SitNumber)//通知所有玩家某个玩家开了奖池 
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 25;
            jd["Msg"] = SitNumber;
            CommandQueue.Enqueue(jd.ToJson());
        
        }
        void Cmd_22() //结算时发给玩家们所有玩家的筹码数量
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 22;
            MyDataBase.instance.ReSetPlayerChipCount(UnRemovablePlayers);
            string s = "/";
            for (int i = 0; i < UnRemovablePlayers.Count;i++ )
            {
                s += string.Format("{0}*{1}", UnRemovablePlayers[i].SitNumber, UnRemovablePlayers[i].ChipCount) + "/";
            }
            jd["Msg"] = s;
            CommandQueue.Enqueue(jd.ToJson());
            IsGameOver = true;
            IsCounting = true;
        }
        void Cmd_4() //发送该轮到执行操作的玩家信息
        { 

            JsonData jd = new JsonData();
            jd["CmdId"] = 4;
            Player p=players[CurrentPlayerIndex];
            int SitNumber = p.SitNumber;
            jd["Msg"] = string.Format("{0}*{1}",SitNumber,Step);
            CommandQueue.Enqueue(jd.ToJson());
            if (p.IsAI)
            {
                Cmd_8();
            }
            else 
            {
                Socket s = ClientSockets[SitNumber];
                if (s == null)
                {
                    Cmd_8();
                }
            }
            IsCountingOpTime = true;
            PlayerOpTimeCounter = 0;
        }
        void Cmd_5() //发送所有玩家该发牌了
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 5;
            jd["Msg"] = string.Format("{0}*{1}*{2}",players[CurrentPlayerIndex].SitNumber,DeckIndex,Step);
            switch(Step)
            {
                case 1:
                case 4:
                    DeckIndex += players.Count;
                    break;
                default:
                    DeckIndex += 1;
                    break;
            }
            CommandQueue.Enqueue(jd.ToJson());
        }
        void Cmd_7(string msg) //通知所有其他玩家某个玩家执行了某个操作
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 7;
            jd["Msg"] = msg;
            CommandQueue.Enqueue(jd.ToJson());
        }
        void Cmd_8() //通知某个客户端，让他来处理AI逻辑
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 8;
            jd["Msg"] = string.Format("{0}*{1}",players[CurrentPlayerIndex].SitNumber,Step);
            CommandQueue.Enqueue(jd.ToJson());
        }
        void Cmd_9() //通知某个客户端，让他来告诉我庄家的名牌是不是A
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 9;
            CommandQueue.Enqueue(jd.ToJson());
        }
        void Cmd_23(string msg)//告诉所有玩家某个玩家进行了托管操作
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 23;
            jd["Msg"] = msg;
            CommandQueue.Enqueue(jd.ToJson());
        }
        public void Cmd_500() 
        {
            JsonData jd = new JsonData();
            jd["CmdId"] = 500;
            CommandQueue.Enqueue(jd.ToJson());
        }
        void Req_500(JsonData jd) 
        {
         int SitNumber=(int)jd["Msg"];
         dic[ClientSockets[SitNumber]]=1;
        }
        void HandleNoResponsePlayers()//处理没反应的玩家
        {
            Dictionary<Socket, int>.KeyCollection kc = dic.Keys;
            Socket[] s=new Socket[kc.Count];
            kc.CopyTo(s,0);
            for (int i = 0; i < s.Length;i++)
            {
                int index = GetSocketIndex(s[i]);
                if(!UnRemovablePlayers[index].IsPausedGame)
                {
                    if (dic[s[i]] == 0)
                    {
                        if (!UnResponsePlayerList.Contains(s[i]))
                        {
                         UnResponsePlayerList.Add(s[i]);
                        }
                    }
                    else dic[s[i]] =0;
                }
            }
        }
        void DisConnectInSeconds(int n)//5秒之后还是没响应，直接断开连接
        {
            if (UnResponsePlayerList.Count==0)
            {
                return;
            }
            List<Socket> lst = UnResponsePlayerList;
            ReconnectCounter += n;
            if (ReconnectCounter >= 5000)
            {
                for (int i = 0; i < lst.Count; i++)
                {
                    JsonData jd = new JsonData();
                    jd["ReqId"] = 16;
                    jd["Msg"] = GetSocketIndex(lst[i]);
                    UnResponsePlayerList.Remove(lst[i]);
                    RequestQueue.Enqueue(jd.ToJson());
                }
                ReconnectCounter = 0;
            }
        }
        void StateChecker(int n)//状态计数器
        {
            StateTimeCounter += n;
            if(StateTimeCounter>=5000)
            {
                switch (state)
                {
                    case State.Send:
                        Cmd_500();
                        state = State.Recieve;
                        break;
                    case State.Recieve:
                        HandleNoResponsePlayers();
                        Cmd_500();
                        state = State.Send;
                        break;
                }
                StateTimeCounter = 0;
            }
            DisConnectInSeconds(n);
        }
        int GetRandomTime()
        {
            int time = 0;
            Random r = new Random();
            int n = r.Next(1, 101);
            if (n >= 1 && n <= 15)
            {
                time = 1;
            }
            else if (n >= 16 && n < 31)
            {
                time = 2;
            }
            else if (n >= 31 && n < 46)
            {
                time = 3;
            }
            else if (n >= 46 && n < 61)
            {
                time = 4;
            }
            else if (n >= 61 && n < 71)
            {
                time = 5;
            }
            else if (n >= 71 && n < 81)
            {
                time = 6;
            }
            else if (n >= 81 && n < 91)
            {
                time = 7;
            }
            else if (n >= 91 && n < 95)
            {
                time = 8;
            }
            else if (n >= 95 && n < 98)
            {
                time = 9;
            }
            else if (n >= 98 && n <= 100)
            {
                time = 10;
            }
           // time = 1;
            return time*1000;
        }
    }
    class LogInServer 
    {
       
        public int Port = 8999;
        Socket ServerSocket_V4 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPAddress Address_V4 = IPAddress .Parse("172.31.26.180");
        public LogInServer()
        {

            ServerSocket_V4.Bind(new IPEndPoint(Address_V4, Port));
            Console.WriteLine("Listening:" + Address_V4 + ":" + Port);
            ServerSocket_V4.Listen(100);
            new Thread(ListenForPlayerLogIn_V4).Start();
        }
        void ListenForPlayerLogIn_V4()
        {
            while (true)
            {
                try
                {

                    Socket ClientSocket = ServerSocket_V4.Accept();
                    byte[] buffer = new byte[1024 * 8];
                    int count = ClientSocket.Receive(buffer);
                    byte[] buffer2 = new byte[count];
                    for (int i = 0; i < buffer2.Length; i++)
                    {
                        buffer2[i] = buffer[i];
                    }
                    string msg = Encoding.UTF8.GetString(buffer2);
                    string[] t = msg.Split('%');
                    string ReqId = t[0];
                    string content = t[1];
                    string PlayerProperty = null;
                    string MsgToClient = null;
                    DateTime CurrentTime = DateTime.Now;
                    int val = 0;
                    int NewDay = 0;
                    switch (ReqId)
                    {
                        case "LogIn":
                            PlayerProperty = MyDataBase.instance.LogIn(content, out val, out NewDay);
                            MsgToClient = ReqId + "%" + PlayerProperty + "#" + val + "#" + NewDay + "#" + CurrentTime + "#";
                            break;
                        case "Update":
                            MyDataBase.instance.Update(content, false);
                            MsgToClient = ReqId + "%" + CurrentTime + "#" + content + "#";
                            break;
                        case "GetLow":
                            val = MyDataBase.instance.SetValue(1, int.Parse(content), out NewDay);
                            MsgToClient = ReqId + "%" + CurrentTime + "#" + val + "#";
                            break;
                        case "GetReward":
                            int id = int.Parse(content.Split('*')[0]);
                            val = MyDataBase.instance.SetValue(2, id, out NewDay);
                            MsgToClient = ReqId + "%" + CurrentTime + "#" + val + "#";
                            break;
                        case "Validate":

                            break;
                    }
                    ClientSocket.Send(Encoding.UTF8.GetBytes(MsgToClient));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                }
            }
        }
    }
    class MyDataBase 
    {
        string ConStr = "Data Source=localhost;Database=poker;User ID=tony;Password=tohnyaz";
        public static MyDataBase instance;
        public MyDataBase() {
             instance = this;
        }
        void ResetVipClient()//到时间以后取消VIP资格
        {
            string CmdText = "SELECT * FROM  player where id>0&&VipLevel>0";
            MySqlConnection con = new MySqlConnection(ConStr);
            con.Open();
            MySqlCommand cmd = new MySqlCommand(CmdText,con);
            MySqlDataAdapter mda = new MySqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            mda.Fill(ds,"m");
            DataTable dt=ds.Tables["m"];
            for (int i = 0; i < dt.Rows.Count;i++ )
            {
                DateTime time = (DateTime)dt.Rows[i][13];
                int BuyVipDay = time.Day;
                int NowaDay = DateTime.Now.Day;
                int delta = BuyVipDay - NowaDay;
                int id=(int)dt.Rows[i][0];
                if(delta>=0)
                {
                    CmdText =string .Format( "update player set VipLevel=0 where id={0}",id);
                    cmd.CommandText = CmdText;
                    cmd.ExecuteNonQuery();
                }

            }
            con.Close();
        }
        public void ChangeChipCount(Player p,int Amount)
        {
            MySqlConnection con = new MySqlConnection(ConStr);
            p.ChipCount -= Amount;
            if(p.ChipCount<0)
            {
                p.ChipCount = 0;
                p.MyRoom.IsPlayerAllIn = 1;
            }
            string CmdText ="";
            if(p.IsAI){
                CmdText = string .Format("UPDATE ai SET ChipCount={0} WHERE (Id={1})",p.ChipCount,p.Id);
            }
            else CmdText = string.Format("UPDATE player SET ChipCount={0} WHERE (Id={1})", p.ChipCount, p.Id);
            con.Open();
            MySqlCommand cmd = new MySqlCommand(CmdText,con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
        public string GetAIProperty(int num)//获取AI的信息
        {
            MySqlConnection con = new MySqlConnection(ConStr);
            con.Open();
            string property = "*";
            string CmdText = string.Format("SELECT * FROM `AI` where ChipCount>={0}&&InGame=0", num);
            MySqlDataAdapter mda = new MySqlDataAdapter(CmdText, con);
            DataSet ds = new DataSet();
            mda.Fill(ds, "MyTable");
            DataTable dt = ds.Tables["MyTable"];
           for (int j = 0; j < dt.Columns.Count; j++)
          {
              property+= dt.Rows[0][j] + "*";
          }
          //将获取到的AI的游戏状态设为1
           int Id=(int)dt.Rows[0][0];
           CmdText = string.Format("update `AI` set InGame=1 where Id={0}",Id);
           MySqlCommand cmd = new MySqlCommand(CmdText,con );
           cmd.ExecuteNonQuery();
           con.Close();
           return property;
        }
        public void SetInGameToZero(int[] ids) 
        {
            MySqlConnection con = new MySqlConnection(ConStr);
            con.Open();
            for (int i = 0; i < ids.Length;i++ )
            {
                string CmdText = string.Format("update `AI` set InGame=0 where Id={0}", ids[i]);
                MySqlCommand cmd = new MySqlCommand(CmdText, con);
                cmd.ExecuteNonQuery();
            }
            con.Close();
        }
        public void ReSetPlayerChipCount(List<Player> ps) 
        {
            int[] ids=new int[ps.Count];
            for (int i = 0; i < ids.Length;i++ )
            {
                ids[i] = ps[i].Id;
            }
            MySqlConnection con = new MySqlConnection(ConStr);
            string CmdText = null;
            MySqlCommand cmd = new MySqlCommand(CmdText,con);
            MySqlDataAdapter mda = new MySqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            DataTable dt = null;
            con.Open();
            for (int i = 0; i < ids.Length; i++)
            {
               string name = "player";
               if(ps[i].IsAI)
               {
                   name = "ai";
               }
               CmdText = string.Format("select ChipCount from {0} where Id={1}",name, ids[i]);
               cmd.CommandText = CmdText;
               mda.Fill(ds,"n");
               dt=ds.Tables["n"];
               ps[i].ChipCount = (int)dt.Rows[i][0];
            }
            con.Close();
        }
        public string LogIn(string msg,out int val,out int NewDay)//玩家登录游戏 
        {
            val = 0;
            NewDay = 0;
            string property = "";
            string[] t = msg.Split('*');
            int Id = int.Parse(t[0]);//先通过玩家发过来的Id号来查询，是不是存在这个玩家.若存在Id，则把信息发给登录游戏的玩家；否则通过PhoneId来查询.
            string PhoneId = t[1];//如果不存在Id，那么通过PhoneId来查询.若存在PhoneId，则把信息发给登录游戏的玩家；否则新建玩家.
            bool f1 = IsNewPlayerId(Id);
            int MyId = 0;
            bool f2 = IsNewPlayerPhoneId(PhoneId,out MyId);
            int priority = 0;
            if (!f1)
            {
                val = SetValue(0, Id,out NewDay);
                property = GetPlayerProperty(Id);
            }
            else priority = 1;

            if(priority==1){
                if (!f2)
                {
                    val = SetValue(0, MyId,out NewDay);
                    property = GetPlayerProperty(MyId);
                }
                else priority = 3;
            
            }
            if(priority==3){
                CreateNewPlayer(PhoneId);
                IsNewPlayerPhoneId(PhoneId, out MyId);
                property = GetPlayerProperty(MyId);
                val = SetValue(0, MyId, out NewDay);
            }
            return property;
        }
        bool IsNewPlayerId(int Id)//通过玩家发过来的Id来判断
        {
            MySqlConnection con = new MySqlConnection(ConStr);
            con.Open();
            string CmdText = string.Format("SELECT * FROM `player` where Id={0}", Id);
            MySqlDataAdapter mda = new MySqlDataAdapter(CmdText ,con);
            DataSet ds = new DataSet();
            mda.Fill(ds,"n");
            DataTable dt = ds.Tables["n"];
            con.Close();
            return dt.Rows.Count==0;
        }
        bool IsNewPlayerPhoneId(string pid,out int Id)//通过玩家发过来的PhoneId来判断
        {
            MySqlConnection con = new MySqlConnection(ConStr);
            con.Open();
            Id = -1;
            string CmdText = string.Format("SELECT * FROM `player` where PhoneId='{0}'", pid);
            MySqlDataAdapter mda = new MySqlDataAdapter(CmdText, con);
            DataSet ds = new DataSet();
            mda.Fill(ds, "n");
            DataTable dt = ds.Tables["n"];
            bool flag = dt.Rows.Count == 0;
            if(!flag)
            {
                Id =(int)dt.Rows[0][0];
            }
            con.Close();
            return flag;
        }
        public string GetPlayerProperty(int id)//通过玩家Id获取真人玩家信息
        {
            MySqlConnection con = new MySqlConnection(ConStr);
            con.Open();
            string property = "*";
            string CmdText = string.Format("SELECT * FROM `player` where Id={0}", id);
            MySqlDataAdapter mda = new MySqlDataAdapter(CmdText, con);
            DataSet ds = new DataSet();
            mda.Fill(ds, "n");
            DataTable dt = ds.Tables["n"];
            for (int i = 0; i < dt.Columns.Count;i++ )
            {
                property += dt.Rows[0][i] + "*";
            }
            con.Close();
            return property;
        }
        public void CreateNewPlayer(string pid)//创建新玩家并返回新玩家的信息
        {
            MySqlConnection con = new MySqlConnection(ConStr);
            string CmdText = string.Format("INSERT INTO `player` ( PhoneId) VALUES ( '{0}')",pid);
            con.Open();
            MySqlCommand cmd = new MySqlCommand(CmdText,con);
            cmd.ExecuteNonQuery();
            con.Close();
           
        }
        public void Update(string s,bool IsAI) 
        {
            string[] t = s.Split('*');
            string ColumnName=t[0];
            object ColumnValue=(object)t[1];
            int id = int.Parse(t[2]);
            string CmdText = null;
            if(IsAI)
            {
                CmdText = string.Format("UPDATE ai SET {0}='{1}' WHERE (Id={2})",ColumnName,ColumnValue,id);
            }
            else CmdText = string.Format("UPDATE player SET {0}='{1}' WHERE (Id={2})", ColumnName, ColumnValue, id);
            MySqlConnection con = new MySqlConnection(ConStr);
            con.Open();
            MySqlCommand cmd = new MySqlCommand(CmdText, con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
        public int SetValue(int i, int id,out int NewDay) //设置某个玩家的某个信息
        {
            NewDay = 0;
            int val = 0;
            int ChipCount = 0;
            int VipLevel = 0;
            int VipCounter = 0;
            int LowCounter = 0;
            int OnLineCounter = 0;
            int amount = 0;
            MySqlConnection con = new MySqlConnection(ConStr);
            con.Open();
            string CmdText =null;
            MySqlCommand cmd = new MySqlCommand(CmdText, con);
            MySqlDataAdapter mda = new MySqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            DataTable dt = null;
            switch(i)
            {
                case 0://查Vip的信息
                    CmdText = string.Format("SELECT {0},{1},{2},{3} FROM  player where id={4} ", "ChipCount","NewDay", "VipLevel", "VipCounter",id);
                    cmd.CommandText = CmdText;
                    mda.Fill(ds,"n");
                    dt=ds.Tables["n"];
                    ChipCount=(int)dt.Rows[0][0];
                    NewDay = (int)dt.Rows[0][1];
                    VipLevel = (int)dt.Rows[0][2];
                    VipCounter = (int)dt.Rows[0][3];
                    if(VipLevel!=0)
                    {
                        if(VipCounter==0)
                        {
                            VipCounter+=1;
                            switch(VipLevel)
                            {
                                    case 1:
                                    amount=50000;
                                    break;
                                    case 2:
                                     amount=100000;
                                    break;
                                     case 3:
                                     amount=150000;
                                    break;
                            }
                            ChipCount += amount;
                        }
                        else if (VipCounter==1)
                        {

                            VipCounter = 2; 
                        }
                    }
                    cmd.CommandText = string.Format("UPDATE  player SET {0}='{1}',{2}='{3}',{4}='{5}' WHERE Id={6}", "ChipCount", ChipCount, "NewDay", 1, "VipCounter", VipCounter, id);
                    cmd.ExecuteNonQuery();
                    val = VipCounter;
                    break;
                case 1://查低保信息
                    CmdText = string.Format("SELECT {0},{1} FROM player where Id={2} ", "ChipCount", "LowCounter", id);
                    cmd.CommandText = CmdText;
                    mda.Fill(ds,"n");
                    dt=ds.Tables["n"];
                    ChipCount=(int)dt.Rows[0][0];
                    LowCounter = (int)dt.Rows[0][1];
                   
                    amount = 5000;
                    if(LowCounter<3)
                    {
                        LowCounter += 1;
                        ChipCount += amount;
                        cmd.CommandText = string.Format("UPDATE player SET {0}='{1}',{2}='{3}' WHERE Id={4}", "ChipCount", ChipCount, "LowCounter", LowCounter, id);
                        cmd.ExecuteNonQuery();
                    }
                    else if (LowCounter==3)
                    {
                        LowCounter = 4;
                    }
                    val = LowCounter;
                    break;
                case 2://查在线信息
                    CmdText = string.Format("SELECT {0},{1} FROM player where Id={2} ", "ChipCount", "OnLineCounter", id);
                    cmd.CommandText = CmdText;
                     mda.Fill(ds,"n");
                    dt=ds.Tables["n"];
                    ChipCount=(int)dt.Rows[0][0];
                    OnLineCounter = (int)dt.Rows[0][1];
                    if (OnLineCounter < 3)
                    {
                        OnLineCounter += 1;
                        switch (OnLineCounter)
                        {
                            case 1:
                                amount += 3000;
                                break;
                            case 2:
                                amount += 5000;
                                break;
                            case 3:
                                amount += 10000;
                                break;
                        }
                        ChipCount += amount;
                        cmd.CommandText = string.Format("UPDATE player SET {0}='{1}',{2}='{3}' WHERE (Id={4})", "ChipCount", ChipCount, "OnLineCounter", OnLineCounter, id);
                        cmd.ExecuteNonQuery();
                    }
                    else if (OnLineCounter==3)
                    {
                        OnLineCounter = 4;
                    }
                    val = OnLineCounter;
                    break;
            }
            con.Close();
            return val;
        }
        public void ResetTableValues()//00：00：00时重置所有玩家的某些数据 
        {
            ResetVipClient();
            MySqlConnection con = new MySqlConnection(ConStr);
            con.Open();
            string CmdText = "UPDATE player SET NewDay=0, VipCounter=0, LowCounter=0, OnLineCounter=0";
            MySqlCommand cmd = new MySqlCommand(CmdText, con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
        public void ChangeCharmValue(Player p, int Amount)
        {
            MySqlConnection con = new MySqlConnection(ConStr);
            p.CharmValue -= Amount;
            string CmdText = "";
            if (p.IsAI)
            {
                CmdText = string.Format("UPDATE ai SET CharmValue='{0}' WHERE (Id={1})", p.CharmValue, p.Id);
               
            }
            else CmdText = string.Format("UPDATE player SET CharmValue='{0}' WHERE (Id={1})", p.CharmValue, p.Id);
            con.Open();
            MySqlCommand cmd = new MySqlCommand(CmdText, con);
            cmd.ExecuteNonQuery();
            con.Close();
           
        }
        
    }
    class Player
    {
        public Room MyRoom;//AI玩家所在的房间
        public int SitNumber;//玩家的座位号
        public string Name;//玩家的名字
        public bool IsAI;//判断是不是电脑AI
        public int Gambling;//电脑AI的赌性
        public int RichDegree;//电脑AI的富裕度
        public int Anxiety;//焦虑度
        public int FriendlyDegree;//友好度
        public int Id;//数据库中的PlayerId
        public string FaceBookId;//真人玩家的facebookId
        public int ChipCount;//身上的筹码数
        public int VipLevel;//VIP等级
        public int Head;//头像的编号
        public int CharmValue;//魅力值
        public int GameCount;//游戏局数
        public int WinCount;//游戏胜利局数
        public float WinRate;//胜率
        public int CardType;//可能性最大的牌的类型号
        public bool IsSee;//记录是不是看牌了
        public int Difference;//牌型差值
        public bool IsReady;//表示这个玩家是不是已经准备了
        public int IsTrustee;//是不是托管玩家
        public bool IsAlreadySendEmoji;//是不是已经发送了表情
        public int RewardPoolState;//开启奖池的状态
        public bool IsPausedGame;//是不是切换程序了
        public int PausedGameTime;//切换出去程序的时间
        public bool IsConnecting;//是不是掉线玩家
        public bool IsThePlayerKickOut;//判断这个玩家被踢出了吗（收不到客户端的确认信息时有用）
        public Player(bool IsAI,Room ss,int sitnum,string property)
        {
        SitNumber = sitnum;
        this.IsAI = IsAI;
        MyRoom = ss;
        if (IsAI)
        {
            SetAIProperty();
            GetReady();
        }
        else 
        {
            SetPlayerProperty(property);
            IsConnecting = true;
        } 
        }
       public void CountTimeWhenPauseGame(int n) 
        {
         if(!IsPausedGame)
         {
             return;
         }
         PausedGameTime += n;
        if(PausedGameTime>=20000)
        {
            JsonData jd = new JsonData();
            jd["ReqId"] = 16;
            jd["Msg"] = SitNumber;
            MyRoom.RequestQueue.Enqueue(jd.ToJson());
            StopCounting();
        }
        }
       public void StopCounting() 
       {
           PausedGameTime = 0;
           IsPausedGame = false;
       }
        void GetReady()
        {
            JsonData jd = new JsonData();
            jd["ReqId"] = 0;
            jd["Msg"] = string.Format("{0}*{1}", SitNumber, 1);
            MyRoom.RequestQueue.Enqueue(jd.ToJson());
        }
        void SetAIProperty()//AI的信息初始化
        {
            string s = MyDataBase.instance.GetAIProperty(MyRoom.MinChipCount);
            string[] t = s.Split('*');
            Id = int.Parse(t[1]);
            Name = t[2];
            Gambling = int.Parse(t[3]);
            RichDegree = int.Parse(t[4]);
            FriendlyDegree = int.Parse(t[5]);
            Anxiety =int.Parse(t[6]);
            ChipCount = int.Parse(t[7]);
            Head = int.Parse(t[8]);
            WinCount = int.Parse(t[9]);
            GameCount = int.Parse(t[10]);
            VipLevel = int.Parse(t[11]);
            CharmValue = int.Parse(t[12]);
            WinRate = (WinCount / GameCount)*100f;
        }
        void SetPlayerProperty(string property)//真人玩家的信息初始化
        {
            string[] t = property.Split('*');
            Id = int.Parse(t[1]);
            FaceBookId = t[2];
            Name = t[3];
            Head = int.Parse(t[4]);
            ChipCount = int.Parse(t[5]);
            WinCount = int.Parse(t[6]);
            GameCount = int.Parse(t[7]);
            CharmValue = int.Parse(t[8]);
            VipLevel = int.Parse(t[9]);
        }
        public string GetPlayerProperty()
        {
            string property = string.Format("{0}#{1}#{2}#{3}#{4}#{5}#{6}#{7}#{8}#{9}#{10}#{11}#{12}", Id, FaceBookId, Name, Head, ChipCount, WinCount,GameCount, CharmValue, VipLevel,RichDegree,FriendlyDegree,Gambling,Anxiety);
            return property;
        }
        public void ExcuteMyOpThread() {
            ExcuteMyChoose();
        }
         bool IsMustAllIn() {

             if(IsSee)
             {
                 if(ChipCount<=2*MyRoom.UpperLimit){
                     return true;
                 }
             }
             else
             {
                 if(ChipCount<=MyRoom.UpperLimit){

                     return true;
                 }

             }
             return false;
         }
         void ExcuteMyChoose()//执行AI的操作
         {
           if (IsMustAllIn())
           {

                AllIn();
                return;

             }
             if(MyRoom.Step>3){
                 See();
                 if(IsMustAllIn()){
                     AllIn();
                     return;
                 }

             }
             int RaisePossibility = 2 * RichDegree + 3 * Gambling;//加注概率
             int CallPossibility = 100 - 2 * RichDegree + 3 * Gambling;//跟注概率
             int FoldPossibility = 0;//弃牌概率
             int ComparePossibility = 0;//比牌概率
             int ShowDownPossibility = 0;//看牌的概率
             int BigRaisePossibility = 0;//加大注的概率
             int SmallRaisePossibility = 0;//加小注的概率
             Random r = new Random();
             int num=r.Next(1,101);
             int[] n = GetRaiseBtnNumber();
             if (MyRoom.Step < 8)
             {
                 int b_delta = 0;//加大注的增加量
                 int m = 0;
                 bool flag=num < RaisePossibility && num > 0;
                 if (n == null||MyRoom.IsPlayerAllIn==1)
                 {
                     flag = false;
                 }
                 if (flag)
                 {
                     switch (CardType)
                     {
                         case 9:
                             m = 50;
                             b_delta = 50;
                             break;
                         case 8:
                             m = 45;
                             b_delta = 40;
                             break;
                         case 7:
                             m = 40;
                             b_delta = 35;
                             break;
                         case 6:
                             m = 35;
                             b_delta = 30;
                             break;
                         case 5:
                             m = 30;
                             b_delta = 20;
                             break;
                         case 4:
                             m = 20;
                             b_delta = 10;
                             break;
                     }
                     int big_raise = RichDegree + 2 * Gambling + b_delta+m;
                     if (num <= big_raise)//加大注
                     {
                         if (n.Length == 2)
                         {
                             Raise(n[1]);
                         }
                         else Raise(n[0]);
                     }
                     else//加小注
                     {
                         Raise(n[0]);

                     }
                 }
                 else
                 {
                     Call();

                 }
             }
             else { 
            
                     switch(Difference){
                         case 9:
                             switch (MyRoom.Step)
                             {
                                 case 8:
                                     CallPossibility = 15+ (int)(0.5f * Gambling);
                                     ComparePossibility = 5 + (int)(0.5f * (RichDegree + Gambling));
                                     ShowDownPossibility = 10 + (int)(0.5f * (RichDegree + Gambling));
                                     FoldPossibility = 70 - Gambling - RichDegree;
                                     RaisePossibility = -1;

                                     break;
                                 case 9:
                                     CallPossibility = 10+ (int)(0.5f * Gambling)-5-5;
                                     ComparePossibility = 5 + (int)(0.5f * (RichDegree + Gambling))+5;
                                     ShowDownPossibility = 15 + (int)(0.5f * (RichDegree + Gambling))+5;
                                     FoldPossibility = 70 - Gambling - RichDegree;
                                     RaisePossibility = -1;
                                     break;
                                 case 10:
                                     CallPossibility = 10+ (int)(0.5f * Gambling)-5;
                                     ComparePossibility = 5 + (int)(0.5f * (RichDegree + Gambling))-5;
                                     ShowDownPossibility = 15 + (int)(0.5f * (RichDegree + Gambling))+10;
                                     FoldPossibility = 70 - Gambling - RichDegree+5;
                                     RaisePossibility = -1;
                                     break;
                                 case 11:
                                     CallPossibility = 10+ (int)(0.5f * Gambling)-10;
                                     ComparePossibility = 5 + (int)(0.5f * (RichDegree + Gambling))-5+5;
                                     ShowDownPossibility = 15 + (int)(0.5f * (RichDegree + Gambling))+15-10;
                                     FoldPossibility = 70 - Gambling - RichDegree+5;
                                     RaisePossibility = -1;
                                     break;
                                 case 12:
                                     CallPossibility = 10+ (int)(0.5f * Gambling)-5-10;
                                     ComparePossibility = 5 + (int)(0.5f * (RichDegree + Gambling))-5+5;
                                     ShowDownPossibility = 15 + (int)(0.5f * (RichDegree + Gambling))+20;
                                     FoldPossibility = 70 - Gambling - RichDegree+5-10;
                                     RaisePossibility = -1;
                                     break;
                             }
                             break;
                              case 8:
                             switch (MyRoom.Step)
                             {
                                 case 8:
                                     CallPossibility = 20 + (int)(0.5f * Gambling);
                                     ComparePossibility = 20 + (int)(0.5f * RichDegree);
                                     ShowDownPossibility = 30 + (int)(0.5f * (RichDegree + Gambling));
                                     FoldPossibility = 25 - Gambling - RichDegree;
                                     RaisePossibility =5+(int)(0.5f*(RichDegree+Gambling));
                                     BigRaisePossibility = 0 + (int)(0.3f * (RichDegree + Gambling));
                                     SmallRaisePossibility = 5 + (int)(0.2f * (RichDegree + Gambling));

                                     break;
                                 case 9:
                                      CallPossibility = 20 + (int)(0.5f * Gambling)-5-5;
                                     ComparePossibility = 20 + (int)(0.5f * RichDegree)+5;
                                     ShowDownPossibility = 30 + (int)(0.5f * (RichDegree + Gambling))+5;
                                     FoldPossibility = 25 - Gambling - RichDegree;
                                     RaisePossibility =5+(int)(0.5f*(RichDegree+Gambling));
                                     BigRaisePossibility = 0 + (int)(0.3f * (RichDegree + Gambling));
                                     SmallRaisePossibility = 5 + (int)(0.2f * (RichDegree + Gambling));
                                     break;
                                 case 10:
                                     CallPossibility = 20 + (int)(0.5f * Gambling)-5;
                                     ComparePossibility = 20 + (int)(0.5f * RichDegree)-5;
                                     ShowDownPossibility = 30 + (int)(0.5f * (RichDegree + Gambling))+10-5;
                                     FoldPossibility = 25 - Gambling - RichDegree+5;
                                     RaisePossibility =5+(int)(0.5f*(RichDegree+Gambling));
                                     BigRaisePossibility = 0 + (int)(0.3f * (RichDegree + Gambling));
                                     SmallRaisePossibility = 5 + (int)(0.2f * (RichDegree + Gambling));
                                     break;
                                 case 11:
                                     CallPossibility = 20 + (int)(0.5f * Gambling)-10;
                                     ComparePossibility = 20 + (int)(0.5f * RichDegree)-5+5;
                                     ShowDownPossibility = 30 + (int)(0.5f * (RichDegree + Gambling))+15-10;
                                     FoldPossibility = 25 - Gambling - RichDegree+5;
                                     RaisePossibility =5+(int)(0.5f*(RichDegree+Gambling));
                                     BigRaisePossibility = 0 + (int)(0.3f * (RichDegree + Gambling));
                                     SmallRaisePossibility = 5 + (int)(0.2f * (RichDegree + Gambling));
                                     break;
                                 case 12:
                                     CallPossibility = 20 + (int)(0.5f * Gambling)-5-10;
                                     ComparePossibility = 20 + (int)(0.5f * RichDegree)-5+5;
                                     ShowDownPossibility = 30 + (int)(0.5f * (RichDegree + Gambling))+20;
                                     FoldPossibility = 25 - Gambling - RichDegree-10+5;
                                     RaisePossibility =5+(int)(0.5f*(RichDegree+Gambling));
                                     BigRaisePossibility = 0 + (int)(0.3f * (RichDegree + Gambling));
                                     SmallRaisePossibility = 5 + (int)(0.2f * (RichDegree + Gambling));
                                     break;
                             }
                             break;
                              case 7:
                             switch (MyRoom.Step)
                             {
                                 case 8:
                                     CallPossibility = 30 + (int)(0.5f * Gambling);
                                     ComparePossibility = 15 ;
                                     ShowDownPossibility = 15 ;
                                     FoldPossibility = 20 - (int)(0.5f * RichDegree) - Gambling;
                                     RaisePossibility = 20 + (int)(0.5f * (RichDegree + Gambling));
                                     BigRaisePossibility = 10 + (int)(0.3f * (RichDegree + Gambling));
                                     SmallRaisePossibility = 10 + (int)(0.2f * (RichDegree + Gambling));
                                     break;
                                 case 9:
                                     CallPossibility = 30 + (int)(0.5f * Gambling)-5-5;
                                     ComparePossibility = 15+5 ;
                                     ShowDownPossibility = 15+5 ;
                                     FoldPossibility = 20 - (int)(0.5f * RichDegree) - Gambling;
                                     RaisePossibility = 20 + (int)(0.5f * (RichDegree + Gambling));
                                     BigRaisePossibility = 10 + (int)(0.3f * (RichDegree + Gambling));
                                     SmallRaisePossibility = 10 + (int)(0.2f * (RichDegree + Gambling));
                                     break;
                                 case 10:
                                      CallPossibility = 30 + (int)(0.5f * Gambling)-5;
                                     ComparePossibility = 15 -5;
                                     ShowDownPossibility = 15+10-5 ;
                                     FoldPossibility = 20 - (int)(0.5f * RichDegree) - Gambling+5;
                                     RaisePossibility = 20 + (int)(0.5f * (RichDegree + Gambling));
                                     BigRaisePossibility = 10 + (int)(0.3f * (RichDegree + Gambling));
                                     SmallRaisePossibility = 10 + (int)(0.2f * (RichDegree + Gambling));
                                     break;
                                 case 11:
                                      CallPossibility = 30 + (int)(0.5f * Gambling)-10;
                                     ComparePossibility = 15-5+5 ;
                                     ShowDownPossibility = 15+15-10 ;
                                     FoldPossibility = 20 - (int)(0.5f * RichDegree) - Gambling+5;
                                     RaisePossibility = 20 + (int)(0.5f * (RichDegree + Gambling));
                                     BigRaisePossibility = 10 + (int)(0.3f * (RichDegree + Gambling));
                                     SmallRaisePossibility = 10 + (int)(0.2f * (RichDegree + Gambling));
                                     break;
                                 case 12:
                                     CallPossibility = 30 + (int)(0.5f * Gambling)-5-10;
                                     ComparePossibility = 15 -5+5;
                                     ShowDownPossibility = 15+20 ;
                                     FoldPossibility = 20 - (int)(0.5f * RichDegree) - Gambling-10+5;
                                     RaisePossibility = 20 + (int)(0.5f * (RichDegree + Gambling));
                                     BigRaisePossibility = 10 + (int)(0.3f * (RichDegree + Gambling));
                                     SmallRaisePossibility = 10 + (int)(0.2f * (RichDegree + Gambling));
                                     break;
                             }
                             break;
                              case 6:
                             switch (MyRoom.Step)
                             {
                                 case 8:
                                     CallPossibility = 35 -RichDegree-Gambling;
                                     ComparePossibility = 15+(int)(0.5f*RichDegree);
                                     ShowDownPossibility = 15;
                                     FoldPossibility = 10 - (int)(0.5f * RichDegree);
                                     RaisePossibility = 25 + RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree +0.6f*Gambling);
                                     SmallRaisePossibility = 15 + (int)(0.6f * RichDegree + 0.4f*Gambling);
                                     break;
                                 case 9:
                                    CallPossibility = 35 -RichDegree-Gambling-5-5;
                                     ComparePossibility = 15+(int)(0.5f*RichDegree)+5;
                                     ShowDownPossibility = 15+5;
                                     FoldPossibility = 10 - (int)(0.5f * RichDegree);
                                     RaisePossibility = 25 + RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree +0.6f*Gambling);
                                     SmallRaisePossibility = 15 + (int)(0.6f * RichDegree + 0.4f*Gambling);
                                     break;
                                 case 10:
                                    CallPossibility = 35 -RichDegree-Gambling-5;
                                     ComparePossibility = 15+(int)(0.5f*RichDegree)-5;
                                     ShowDownPossibility = 15+10-5;
                                     FoldPossibility = 10 - (int)(0.5f * RichDegree)+5;
                                     RaisePossibility = 25 + RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree +0.6f*Gambling);
                                     SmallRaisePossibility = 15 + (int)(0.6f * RichDegree + 0.4f*Gambling);
                                     break;
                                 case 11:
                                    CallPossibility = 35 -RichDegree-Gambling-10;
                                     ComparePossibility = 15+(int)(0.5f*RichDegree)-5+5;
                                     ShowDownPossibility = 15+15-10;
                                     FoldPossibility = 10 - (int)(0.5f * RichDegree)+5;
                                     RaisePossibility = 25 + RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree +0.6f*Gambling);
                                     SmallRaisePossibility = 15 + (int)(0.6f * RichDegree + 0.4f*Gambling);
                                     break;
                                 case 12:
                                    CallPossibility = 35 -RichDegree-Gambling-5-10;
                                     ComparePossibility = 15+(int)(0.5f*RichDegree)-5+5;
                                     ShowDownPossibility = 15+20;
                                     FoldPossibility = 10 - (int)(0.5f * RichDegree)-10+5;
                                     RaisePossibility = 25 + RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree +0.6f*Gambling);
                                     SmallRaisePossibility = 15 + (int)(0.6f * RichDegree + 0.4f*Gambling);
                                     break;
                             }
                             break;
                              case 5:
                             switch (MyRoom.Step)
                             {
                                 case 8:
                                     CallPossibility = 35 - RichDegree - Gambling;
                                     ComparePossibility = 10 ;
                                     ShowDownPossibility = 20;
                                     FoldPossibility = 5 ;
                                     RaisePossibility = 30 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 15 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 9:
                                      CallPossibility = 35 - RichDegree - Gambling-5-5;
                                     ComparePossibility = 10 +5;
                                     ShowDownPossibility = 20+5;
                                     FoldPossibility = 5 ;
                                     RaisePossibility = 30 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 15 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 10:
                                      CallPossibility = 35 - RichDegree - Gambling-5;
                                     ComparePossibility = 10 -5;
                                     ShowDownPossibility = 20+10-5;
                                     FoldPossibility = 5+5 ;
                                     RaisePossibility = 30 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 15 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 11:
                                      CallPossibility = 35 - RichDegree - Gambling-10;
                                     ComparePossibility = 10 -5+5;
                                     ShowDownPossibility = 20+15-10;
                                     FoldPossibility = 5 +5;
                                     RaisePossibility = 30 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 15 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 12:
                                     CallPossibility = 35 - RichDegree - Gambling-5-10;
                                     ComparePossibility = 10-5+5 ;
                                     ShowDownPossibility = 20+20;
                                     FoldPossibility = 5-10+5 ;
                                     RaisePossibility = 30 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 15 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                             }
                             break;
                              case 4:
                             switch (MyRoom.Step)
                             {
                                 case 8:
                                     CallPossibility = 40 - RichDegree - Gambling;
                                     ComparePossibility = 10;
                                     ShowDownPossibility = 15;
                                     FoldPossibility = 0;
                                     RaisePossibility = 35+ RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 25 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 9:
                                    CallPossibility = 40 - RichDegree - Gambling-5-5;
                                     ComparePossibility = 10+5;
                                     ShowDownPossibility = 15+5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 35+ RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 25 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 10:
                                     CallPossibility = 40 - RichDegree - Gambling-5-5;
                                     ComparePossibility = 10-5;
                                     ShowDownPossibility = 15+10+5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 35+ RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 25 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 11:
                                    CallPossibility = 40 - RichDegree - Gambling-10-10;
                                     ComparePossibility = 10-5+5;
                                     ShowDownPossibility = 15+15+5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 35+ RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 25 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 12:
                                    CallPossibility = 40 - RichDegree - Gambling-10-10;
                                     ComparePossibility = 10-10+5;
                                     ShowDownPossibility = 15+20+5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 35+ RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 25 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                             }
                             break;
                              case 3:
                             switch (MyRoom.Step)
                             {
                                 case 8:
                                     CallPossibility = 40 - RichDegree - Gambling;
                                     ComparePossibility = 10;
                                     ShowDownPossibility = 0;
                                     FoldPossibility = 0;
                                     RaisePossibility = 50 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 35 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 9:
                                     CallPossibility = 40 - RichDegree - Gambling - 5 - 5;
                                     ComparePossibility = 10 + 5;
                                     ShowDownPossibility = 0 + 5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 50 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 35 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 10:
                                     CallPossibility = 40 - RichDegree - Gambling - 5 - 5;
                                     ComparePossibility = 10 - 5;
                                     ShowDownPossibility = 0 + 10 + 5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 50 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 35 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 11:
                                     CallPossibility = 40 - RichDegree - Gambling - 10 - 10;
                                     ComparePossibility = 10 - 5 + 5;
                                     ShowDownPossibility = 0 + 15 + 5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 50 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 35 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 12:
                                     CallPossibility = 40 - RichDegree - Gambling - 10 - 10;
                                     ComparePossibility = 10 - 10 + 5;
                                     ShowDownPossibility = 0 + 20 + 5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 50 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 35 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                             }
                             break;
                              case 2:
                             switch (MyRoom.Step)
                             {
                                 case 8:
                                     CallPossibility = 40 - RichDegree - Gambling;
                                     ComparePossibility = 5;
                                     ShowDownPossibility = 0;
                                     FoldPossibility = 0;
                                     RaisePossibility = 55 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 40 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 9:
                                     CallPossibility = 40 - RichDegree - Gambling - 5 - 5;
                                     ComparePossibility = 5 + 5;
                                     ShowDownPossibility = 0 + 5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 55 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 40 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 10:
                                     CallPossibility = 40 - RichDegree - Gambling - 5 - 5;
                                     ComparePossibility = 5 - 5;
                                     ShowDownPossibility = 0 + 10 + 5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 55 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 40 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 11:
                                     CallPossibility = 40 - RichDegree - Gambling - 10 - 10;
                                     ComparePossibility = 5 - 5 + 5;
                                     ShowDownPossibility = 0 + 15 + 5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 55 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 40 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 12:
                                     CallPossibility = 40 - RichDegree - Gambling - 10 - 10;
                                     ComparePossibility = 5 - 10 + 5;
                                     ShowDownPossibility = 0 + 20 + 5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 55 + RichDegree + Gambling;
                                     BigRaisePossibility = 15 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 40 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                             }
                             break;
                              case 1:
                             switch (MyRoom.Step)
                             {
                                 case 8:
                                     CallPossibility = 40 - RichDegree - Gambling;
                                     ComparePossibility = 0;
                                     ShowDownPossibility = 0;
                                     FoldPossibility = 0;
                                     RaisePossibility = 60 + RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 50 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 9:
                                     CallPossibility = 40 - RichDegree - Gambling - 5 - 5;
                                     ComparePossibility = 0 + 5;
                                     ShowDownPossibility = 0 + 5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 60 + RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 50 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 10:
                                     CallPossibility = 40 - RichDegree - Gambling - 5 - 5;
                                     ComparePossibility = 0 - 5;
                                     ShowDownPossibility = 0 + 10 + 5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 60 + RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 50 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 11:
                                     CallPossibility = 40 - RichDegree - Gambling - 10 - 10;
                                     ComparePossibility = 0 - 5 + 5;
                                     ShowDownPossibility = 0 + 15 + 5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 60 + RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 50 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                                 case 12:
                                     CallPossibility = 40 - RichDegree - Gambling - 10 - 10;
                                     ComparePossibility = 0 - 10 + 5;
                                     ShowDownPossibility = 0 + 20 + 5;
                                     FoldPossibility = 0;
                                     RaisePossibility = 60 + RichDegree + Gambling;
                                     BigRaisePossibility = 10 + (int)(0.4f * RichDegree + 0.6f * Gambling);
                                     SmallRaisePossibility = 50 + (int)(0.6f * RichDegree + 0.4f * Gambling);
                                     break;
                             }
                             break;
                              case 0:
                                     CallPossibility = 0;
                                     ComparePossibility = 0;
                                     ShowDownPossibility = 0;
                                     FoldPossibility = 0;
                                     RaisePossibility = 100;
                                     BigRaisePossibility = 100;
                                     SmallRaisePossibility = 0;
                             break;
                     
                     }
                     bool f1 =num>0&&num<RaisePossibility;//加注
                     bool f2 = num > RaisePossibility && (num < RaisePossibility + CallPossibility);//跟注
                     bool f3=num>(RaisePossibility+CallPossibility)&&num<(RaisePossibility+CallPossibility+FoldPossibility);//弃牌
                     bool f4 = num > (RaisePossibility + CallPossibility+FoldPossibility) && num < (RaisePossibility + CallPossibility + FoldPossibility+ComparePossibility);//比牌
                     bool f5 = num > (RaisePossibility + CallPossibility + FoldPossibility+ComparePossibility) && num < (RaisePossibility + CallPossibility + FoldPossibility + ComparePossibility+ShowDownPossibility);//开牌
                     if(MyRoom.IsPlayerAllIn==1||n==null){
                         f1 = false;
                     }
                     if (f1)
                     {
                         if (num <= BigRaisePossibility)//加大注
                         {
                             if (n.Length == 2)
                             {
                                 Raise(n[1]);
                             }
                             else Raise(n[0]);
                         }
                         else//加小注
                         {
                             Raise(n[0]);

                         }
                     }
                     else if (f2)
                     {
                         Call();
                     }
                     else if (f3)
                     {
                         Fold();
                     }
                     else if (f4)
                     {
                         Compare();
                     }
                     else if (f5)
                     {
                         ShowDown();
                     }
                     else Call();
             }
         }
         void See() //看牌
         {
         if(IsSee){
             return;
         }
         Random r = new Random();
         int num = r.Next(1,100);
         bool f =num <= 10;
         IsSee = f;
         if(f){
         JsonData jd = new JsonData();
         jd["ReqId"] = 1;
         jd["Msg"] = "See";
         jd["SitNumber"] = SitNumber;
         MyRoom.RequestQueue.Enqueue(jd.ToJson());
         }
         }
         public void Call() //跟注
         {
             JsonData jd = new JsonData();
             jd["ReqId"] = 1;
             jd["Msg"] = "Call";
             jd["SitNumber"] = SitNumber;
             MyRoom.RequestQueue.Enqueue(jd.ToJson());
         }
         void AllIn() {//全押
             JsonData jd = new JsonData();
             jd["ReqId"] = 1;
             jd["Msg"] = "AllIn";
             jd["SitNumber"] = SitNumber;
             MyRoom.RequestQueue.Enqueue(jd.ToJson());
         }
         void ShowDown(){//看牌
             JsonData jd1 = new JsonData();
             jd1["ReqId"] = 1;
             jd1["Msg"] = "CallBeforeShowDown";
             jd1["SitNumber"] = SitNumber;
             MyRoom.RequestQueue.Enqueue(jd1.ToJson());
             JsonData jd = new JsonData();
             jd["ReqId"] = 1;
             jd["Msg"] = "ShowDown";
             jd["SitNumber"] = SitNumber;
             MyRoom.RequestQueue.Enqueue(jd.ToJson());
         }
         public  void Fold() {//弃牌
             JsonData jd = new JsonData();
             jd["ReqId"] = 1;
             jd["Msg"] = "Fold";
             jd["SitNumber"] = SitNumber;
             MyRoom.RequestQueue.Enqueue(jd.ToJson());
         }
         void Compare() { //比牌
             JsonData jd = new JsonData();
             jd["ReqId"] = 1;
             jd["Msg"] = "CallBeforeCompare";
             jd["SitNumber"] = SitNumber;
             MyRoom.RequestQueue.Enqueue(jd.ToJson());
             JsonData jd1 = new JsonData();
             jd1["ReqId"] = 1;
             jd1["Msg"] = "Compare";
             jd1["SitNumber"] = SitNumber;
             bool flag = true;
             Player p = null;
             while(flag)
             {
                 Random r = new Random();
                 int n=r.Next(0,MyRoom.players.Count);
                 p=MyRoom .players[n];
                 if(p!=this)
                 {
                     flag = false;
                 }
             }
             jd1["Players"] = string.Format("{0}%{1}", this.SitNumber, p.SitNumber);
             MyRoom.RequestQueue.Enqueue(jd1.ToJson());
         }
         void Raise(int i)//加注
         {
             JsonData jd = new JsonData();
             jd["ReqId"] = 1;
             jd["Msg"] = "Raise";
             jd["SitNumber"] = SitNumber;
             string NextCode = "0";
             string OriginCode = MyRoom.OriginCode;
             switch (i)
             {
                 case 1:
                     NextCode = "0";
                     break;
                 case 2:
                     if (OriginCode == "0")
                     {
                         NextCode = "00";
                     }
                     else if (OriginCode == "0011")
                     {
                         NextCode = "222222";
                     }
                     break;
                 case 3:
                     NextCode = "1";
                     break;
                 case 4:
                     if (OriginCode == "1")
                     {
                         NextCode = "10";
                     }
                     else if (OriginCode == "00")
                     {
                         NextCode = "000";
                     }
                     else if (OriginCode == "0000")
                     {
                         NextCode = "222222";
                     }
                     else if (OriginCode == "0010")
                     {
                         NextCode = "222222";
                     }
                     else if (OriginCode == "011")
                     {
                         NextCode = "222222";
                     }
                     else if (OriginCode == "100")
                     {
                         NextCode = "222222";
                     }
                     break;
                 case 6:
                     if (OriginCode == "0")
                     {
                         NextCode = "01";
                     }
                     else if (OriginCode == "00")
                     {
                         NextCode = "001";
                     }
                     else if (OriginCode == "01")
                     {
                         NextCode = "010";
                     }
                     else if (OriginCode == "001")
                     {
                         NextCode = "0010";
                     }
                     else if (OriginCode == "010")
                     {
                         NextCode = "222222";
                     }
                     break;
                 case 8:
                     if (OriginCode == "1")
                     {
                         NextCode = "11";
                     }
                     else if (OriginCode == "10")
                     {
                         NextCode = "100";
                     }
                     else if (OriginCode == "01")
                     {
                         NextCode = "011";
                     }
                     else if (OriginCode == "001")
                     {
                         NextCode = "0011";
                     }
                     else if (OriginCode == "000")
                     {
                         NextCode = "0000";
                     }
                     else if (OriginCode == "11")
                     {
                         NextCode = "222222";
                     }
                     break;
                 case 12:
                     NextCode = "222222";
                     break;
             }
             jd["OriginCode"] = NextCode;
             jd["RaiseAmount"] = i;
             MyRoom.RequestQueue.Enqueue(jd.ToJson());
         }
         int[] GetRaiseBtnNumber()
         {//获取要显示的加注按钮的索引
             int[] n = null;
             string OriginCode = MyRoom.OriginCode;
             switch (OriginCode)
             {
                 case "111111":
                     n = new int[2] { 1, 3 };
                     break;
                 case "0":
                     n = new int[2] { 2, 6 };
                     break;
                 case "1":
                     n = new int[2] { 4, 8 };
                     break;
                 case "00":
                     n = new int[2] { 4, 6 };
                     break;
                 case "10":
                     n = new int[2] { 8, 12 };
                     break;
                 case "000":
                     n = new int[2] { 8, 12 };
                     break;
                 case "01":
                     n = new int[2] { 6, 8 };
                     break;
                 case "001":
                     n = new int[2] { 6, 8 };
                     break;
                 case "010":
                     n = new int[1] { 6 };
                     break;
                 case "0010":
                     n = new int[1] { 4 };
                     break;
                 case "11":
                     n = new int[1] { 8 };
                     break;
                 case "100":
                     n = new int[1] { 4 };
                     break;
                 case "011":
                     n = new int[1] { 4 };
                     break;
                 case "0011":
                     n = new int[1] { 2 };
                     break;
                 case "0000":
                     n = new int[1] { 4 };
                     break;
             }
             return n;
         }
         public void SendEmojiOrGift(string s)
         {
             JsonData jd = new JsonData();
             jd["ReqId"] = 11;
             jd["Msg"] = s;
             MyRoom.RequestQueue.Enqueue(jd.ToJson());
         }
    }
    struct MyAsyncState
    {
        public int Index;
        public Socket s;
        public byte[] buffer;
        public MyAsyncState(int i, Socket socket,byte[] b)
        {
            Index = i;
            s = socket;
            buffer = b;
        }

    }
}

